Ricardo
Ricardo

Reputation: 1

How can i solve a Scanner error when i click on enter

Scanner scan = new Scanner (System.in);
mainMenu = scan.nextLine().charAt(0);

Soo each time i click on enter it "explodes" and says:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(Unknown Source)
    at tESTedit.main(tESTedit.java:50). 

How can i fix this ?

Upvotes: 0

Views: 72

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191963

Just check the string has content

Scanner scan = new Scanner (System.in);
String input = null;

if (scan.hasNextLine() && !(input = scan.nextLine()).isEmpty()) {
  char mainMenu = input.charAt(0);
  // do something else
} else {
  System.err.println("Nothing was entered");
}

System.out.println("Hello " + input);

Upvotes: 2

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You should never try to access an index from a String or array without checking its length and write a safer code like this,

Scanner scan = new Scanner (System.in);
if (scan.hasNextLine()) {
    String s = scan.nextLine();
    if (s.length() > 0) {
        char mainMenu = s.charAt(0);
        System.out.println(mainMenu);
    }
}
scan.close();

Upvotes: 1

Related Questions