Programmers learn & share
0 votes
97 views

Problem :

I am new to string handling & getting below error while trying to execute a program
java.lang.stringindexoutofboundsexception: string index out of range: 0
by (6.9k points)   | 97 views

1 Answer

0 votes

Solution :

This problem generally occurs when any line is empty . Then it will not find any character at index 0 so the error is thrown.

To fix the issue, one can check the length of line before one uses charAt:

System.out.println(currentline);
char y;
if (currentline.length() < 1) {
   System.out.println("the current line is empty");
} else {
    y = currentline.charAt(0);

    while((currentline.charAt(0)!='/')&&(Character.isWhitespace(y)==false))
    {
       currentline = inputFile.nextLine();
       if (currentline.length() < 1) {
          System.out.println("current line is empty");
          break;
       }
       y = currentline.charAt(0);
       System.out.println(currentline);
       System.out.println(y);
    }
}

Further Readings:

https://github.com/vert-x3/issues/issues/329

by (36.1k points)  
edited by
2,187 questions
2,514 answers
59 comments
241 users