Solution:
The problem happens at the time line
is empty (for example ""
). Then it doesn't have a character at index 0, therefore your error.
To solve, you can inspect the length of line
prior you employ 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);
}
}
Appears like line==""
, first check if the line
String has some content and then attempt to invoke charAt()
.
if(line!=null && line.length()>0) // perform this check to be safe.
First of all, congrats on getting commenced on Java. It's an amazing language and the possibilities are endless. Here is how you can go about solving your error.
The first step is to understand accurately what your error implies, so let's get to that.
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
The type of exception thrown is a StringIndexOutOfBoundsException. Anytime you obtain an IndexOutOfBoundsException (or any type thereof) it implies that you are attempting to access an index in an array that doesn't subsist. By calling the substring system
, you are dividing the string in a character array, and chooosing characters A to B (In your case 0 to 1). In case character 1 doesn't subsist, and else you attempt to access it, it will throw this error.
The cause you are obtaining this error is hence that you are attempting to execute a substring(0,1)
on a String with less than 1 character, aka an empty string or even a null string maybe.
Further, to provide you a quick tip. Generally, a you must make a new method in case your method body extends 12 lines. This will hugely rise the readability of your code. It took me a while to trace the right place for your fix :
Change
if (mots.get(j).startsWith(searchPhrase.substring(0, 1))) {
to
if (searchPhrase != null && searchPhrase.length() > 0 && mots.get(j).startsWith(searchPhrase.substring(0, 1))) {
By doing this you check in case the length of your string is sufficient prior executing the substring method.