Java 空指针访问:该位置的变量只能为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20035122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:31:34  来源:igfitidea点击:

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

javanullpointerexceptionstringbuffer

提问by sky

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:

例外:

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

why this code gives null pointer exception

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

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

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

采纳答案by t0mppa

Are strSet1and strSet2initialized before this? If they are null, you'd get a NullPointerException.

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

* EDIT *

* 编辑 *

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

你不能.append()在一个变量上调用(或任何其他方法)null。将它们初始化为:

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