I'm getting "java.lang.NullPointerException" when I run the following code:
while(StringName[PlaceString] != null){
StringCounter = 0;
while(StringCounter < StringName[PlaceString].length()){
System.out.println("PlaceString: " + PlaceString + " PlaceLine: "
+ PlaceLine + " Length of string: " + StringName[PlaceString].length());
//Does stuff with string
}}
The output is:
PlaceString: 0 PlaceLine: 0 Length of string: 2
Exception in thread "main" java.lang.NullPointerException
The root of the error is:
while(StringCounter < StringName[PlaceString].length()){
although it runs the next line that prints variable's values. I can't figure out why it's complaining about a NullPointer when it can print their values.
Edit: Since I'm not getting a java.lang.StringIndexOutOfBoundsException, the question:
Java substring : string index out of range
didn't help.
答案 0 :(得分:3)
您不会显示所有相关代码,但根据例外及其位置,您很可能在内部PlaceString
期间设置while
的值:
while(StringCounter < StringName[PlaceString].length()){
System.out.println("PlaceString: " + PlaceString + " PlaceLine: "
+ PlaceLine + " Length of string: " + StringName[PlaceString].length());
//Does stuff with string
StringCounter++; // or something close
}
在某次迭代中,StringName[PlaceString]
指的是null
元素
因此,NPE被抛出。
外部while
在这里无济于事:
while(StringName[PlaceString] != null){
因为在内循环终止其迭代之前没有执行。
所以你可以通过在内部while
添加守卫来避免NPE:
while(StringName[PlaceString] != null && StringCounter < StringName[PlaceString].length()){
System.out.println("PlaceString: " + PlaceString + " PlaceLine: "
+ PlaceLine + " Length of string: " + StringName[PlaceString].length());
//Does stuff with string
}