How to Test if a String Index is Null in Java

时间:2018-01-15 18:18:15

标签: java arrays string

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.

1 个答案:

答案 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
}