R. Duggan R. Duggan - 4 months ago 8
Java Question

Dealing with StringIndexOutOfBoundsException in if statement Java

I have a program that gets an input from the console. It checks what the input is then using 'if's it decides what to do. One section test to see what the first four letters of the string are, to see if it needs to deal with it, but not all of the strings are always 4 or more letters long. This means that if you type in something that is less than 4 letters long, it encounters an error, and quits. I can't put that section at the end, because at the end there is an else, which if the command is unknown, is called and something happens. Is there a way I can stop the error from occurring?

My code is:

if(input.equals("help")){
int commandsSize = commands.size();
for(int i = 0; i < commandsSize; i++) {
String value = commands.get(i);
System.out.println(value);
} else if((input.substring(0, 4)).equals("open")) {
...
}

Answer

You can check the size of the string the user inputs,

if (input.length() != 4) {
  System.out.println("You must enter valid input");
  // Probably do something here. 
}

if(input.equals("help")){
    int commandsSize = commands.size();
    for(int i = 0; i < commandsSize; i++) {
      String value = commands.get(i);
      System.out.println(value);
    }
} else if((input.substring(0, 3)).equals("open")) {
...
}