Scanner nextLine-skipping() nach der Verwendung von next() oder nextFoo()?

Ich bin mit der Scanner Methoden nextInt() und nextLine() für das Lesen-Eingang.

Sieht es wie folgt aus:

System.out.println("Enter numerical value");    
int option;
option = input.nextInt(); //Read numerical value from input
System.out.println("Enter 1st string"); 
String string1 = input.nextLine(); //Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); //Read 2nd string (this appears right after reading numerical value)

Das problem ist, dass nach der Eingabe des numerischen Wertes des ersten input.nextLine() übersprungen und der zweite input.nextLine() ausgeführt wird, so dass meine Ausgabe sieht wie folgt aus:

Enter numerical value
3   //This is my input
Enter 1st string    //The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string    //...and this line is executed and waits for my input

Getestet habe ich meine Anwendung und wie es aussieht, das problem liegt in der Verwendung input.nextInt(). Wenn ich es löschen, dann beide string1 = input.nextLine() und string2 = input.nextLine() ausgeführt werden, wie ich Sie haben will.

InformationsquelleAutor der Frage blekione | 2012-10-27

Schreibe einen Kommentar