私はScanner
メソッドnextInt()
とnextLine()
入力の読み取りに使用しています。
次のようになります。
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)
問題は、数値を入力した後、最初の値input.nextLine()
がスキップされて2番目の値input.nextLine()
が実行されるため、出力が次のようになることです。
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
アプリケーションをテストしましたが、問題はの使用にあるようinput.nextInt()
です。削除すると、との両方string1 = input.nextLine()
がstring2 = input.nextLine()
思い通りに実行されます。