-1

I use a Scanner to get inputs from the console in my Java project with this simple code:

char com = ' ';
Scanner sc = new Scanner(System.in);
com = sc.nextLine().charAt(0);

When I enter my expected commands (a,b,c,d...), it works fine, but if I push the Enter button of my keyboard without command entered, I have this error message and the app crash:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

How do I fix this issue?

Malakiof
  • 78
  • 4
  • 17

3 Answers3

0
sc.nextLine().charAt(0);

This get's the 0th character of a String (the first letter of the String).

If you don't enter anything, the String will obviously be empty, so when trying to access the index 0, it will throw a StringIndexOutOfBoundsException.

BetaNyan
  • 25
  • 4
0

You need to define an individual variable that is equal to the user input.

i.e.:

String individualvariable = sc.nextLine();

Then, use individualvariable with .equals to compare strings. In simple terms, you can't just do com = sc.nextLine() first, define com (string, int, boolean), and define a variable of what sc.nextLine() is equal to (x, y, etc.) ; then compare the two variables.

This makes the code easy to read, so take my earlier example and split it up:

String individualvariable;

com = sc.nextLine();

while(individualvariable .equals (com))
{

}

That second block of code I gave you should be the easiest to read, and most simple.

Ruchir Baronia
  • 6,857
  • 4
  • 45
  • 75
-1

Capture the string and parse it independently instead.

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
while(line.equals("")) {
    System.out.println("Nothing entered - try again!");
    line = sc.nextLine();
}
com = line.charAt(0);

The reason it fails is due to the nextLine consuming the newline character; if you enter nothing, then the string will be considered empty as read by nextLine. You want to detect this and allow the user to re-enter the value until they enter something that's not an empty string.

Makoto
  • 96,408
  • 24
  • 164
  • 210