0

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.

Alex O'Connor
  • 80
  • 1
  • 9
  • Looks like duplicate question here https://stackoverflow.com/questions/953527/java-substring-string-index-out-of-range. The answer explains how a utility function is recommended to fix the string null errors that are in your while condition. –  Jan 15 '18 at 18:20
  • Possible duplicate of [Java substring : string index out of range](https://stackoverflow.com/questions/953527/java-substring-string-index-out-of-range) – Vishal Yadav Jan 15 '18 at 18:23
  • 3
    Does "Does stuff with string" change the value of PlaceString or StringName anywhere? – Burrito Jan 15 '18 at 18:26
  • Yes, I do increment all of the counter variables by one using "++" – Alex O'Connor Jan 15 '18 at 18:58

1 Answers1

3

You don't show all the relevant code but according to the exception and its location, you set very probably the value of PlaceString during the inner 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
}

At a certain iteration, StringName[PlaceString] refers to a null element.
So the NPE is thrown.

The outer while will not help here :

while(StringName[PlaceString] != null){

as it is not executed before the inner loop terminates its iterations.

So you could avoid the NPE by adding the guard in the inner while :

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
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215