3

I am writing a program that opens a text file and checks for comments. It then parses through the comments to check for certain words.

The error im having is with the following while loop that checks to see if the current line starts with white space or any character other than '/' if there is a non backslash character there than the while loop moves on to the next line and checks again. Once the while loop meets its requirements and breaks out the program crashes and i get the following output error.

import java.rmi.Naming;
import java.net.InetAddress;
i
import java.lang.reflect.*;
i
ERROR: String index out of range: 0 
at java.lang.String.charAt(Unknown Source) 
at ExtraCredit.main(ExtraCredit.java:22)</code></pre> 

here is the problematic code sample

System.out.println(line);
char x = line.charAt(0);
while((line.charAt(0)!='/')&&(Character.isWhitespace(x)==false))
{
    line = inputFile.nextLine();
    x = line.charAt(0);
    System.out.println(line);
    System.out.println(x);
}

thanks for any help. Im sure its a simple error but im just not seeing it.

Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
John Park
  • 290
  • 2
  • 8
  • 25

4 Answers4

5

The problem occurs when line is empty (e.g. ""). Then it doesn't have a character at index 0, hence your error.

To fix, you can check the length of line before you use charAt:

System.out.println(line);
char x;
if (line.length() < 1) {
   System.out.println("next line is empty");
} else {
    x = line.charAt(0);

    while((line.charAt(0)!='/')&&(Character.isWhitespace(x)==false))
    {
       line = inputFile.nextLine();
       if (line.length() < 1) {
          System.out.println("next line is empty");
          break;
       }
       x = line.charAt(0);
       System.out.println(line);
       System.out.println(x);
    }
}
jh314
  • 27,144
  • 16
  • 62
  • 82
2

Seems like line=="" , first check if the line String has some content and then try to invoke charAt() .

if(line!=null && line.length()>0) // perform this check to be safe.

Look at the documentation of String#charAt().

Throws:

IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

Check for null and positive length.

line = inputFile.nextLine();
if (line != null && line.length() > 0) {
    x = line.charAt(0);
    System.out.println(line);
    System.out.println(x);
}

You should always ensure a check like this has been made, or a guarantee is in place, before accessing objects like this.

Ken
  • 30,811
  • 34
  • 116
  • 155
0

If should use code that won't explode (as your does) when your line is a (zero length) blank, like this:

while (!line.startsWith("\\"))

Even better, check for null too:

while (line != null && !line.startsWith("\\"))

Note that your check for whitespace is redundant, if its a slash, it isn't whitespace.

Bohemian
  • 412,405
  • 93
  • 575
  • 722