i have the following problem: i want to read in a String from the user, so far it works pretty well but everytime i press just “return” i get alway the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at Shell.execute(Shell.java:20)
at Shell.main(Shell.java:55)
This would be the code:
private static void execute(BufferedReader stdin) throws IOException {
boolean quit = false;
Field test = new Field();
while (!quit) {
System.out.print("ch> ");
String input = stdin.readLine();
if (input == null) {
break;
}
String[] tokens = input.trim().split("\\s+");
tokens[0].toLowerCase();
char tmp = tokens[0].charAt(0);
switch (tmp) {
case 'n':
test.setPoints(null);
break;
case 'a':
test.add(new Point(Integer.parseInt(tokens[1]), Integer
.parseInt(tokens[2])));
break;
case 'r':
test.remove(new Point(Integer.parseInt(tokens[1]), Integer
.parseInt(tokens[2])));
break;
case 'p':
System.out.println(test);
break;
case 'c':
System.out.println(test.convexHull());
break;
case 'h':
System.out.println("");
break;
case 'q':
quit = true;
break;
default:
break;
}
}
}
Thanks for your help.
If you get an index out of bounds exception when accessing the 0th element, you string is probably empty. You need to add a check for this, checking for null is not enough.
By the way, when you write like this:
I highly suspect your tokens[0] remains unchanged. Since strings in java are immutable, toLowerCase will have to return a new string which only contains lower case character.