空指针访问:该位置的变量只能为空 [英] Null pointer access: The variable can only be null at this location

查看:30
本文介绍了空指针访问:该位置的变量只能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for(int i=0;i<n;i++){
  for(int j=0;j<26;j++){
    if(str.charAt(i)== strChar.charAt(j) )
    * strSet1.append(str.charAt(i));
  }
    * strSet2.append(str.charAt(i));
}

异常:

Exception in thread "main" java.lang.NullPointerException
  at AterSeries.main(AterSeries.java:33)

为什么这段代码给出空指针异常

why this code gives null pointer exception

警告:空指针访问:变量 strSet1 在此位置只能为空空指针访问:变量strSet2在这个位置只能为空

warning: Null pointer access: The variable strSet1 can only be null at this location Null pointer access: The variable strSet2 can only be null at this location

推荐答案

strSet1strSet2 是否在此之前初始化?如果它们为空,你会得到一个 NullPointerException.

Are strSet1 and strSet2 initialized before this? If they are null, you'd get a NullPointerException.

* 编辑 *

您不能对 null 的变量调用 .append()(或任何其他方法).将它们初始化为:

You cannot call .append() (or any other method) on a variable that is null. Initialize them as:

StringBuffer strSet1 = new StringBuffer();
StringBuffer strSet2 = new StringBuffer();

这篇关于空指针访问:该位置的变量只能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆