入力の読み取りには メソッドと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()
希望どおりに実行されます。
ベストアンサー1
それは、Scanner.nextInt
メソッドは、入力時に「Enter」キーを押して作成された改行文字を読み取らないため、Scanner.nextLine
その改行を読み取った後に戻ります。
使用後にも同様の動作が発生しますScanner.nextLine
。Scanner.next()
または任意のScanner.nextFoo
メソッド(nextLine
それ自体を除く)。
回避策:
Scanner.nextLine
それぞれの後に呼び出しを置くかScanner.nextInt
、改行Scanner.nextFoo
を含むその行の残りを消費しますint option = input.nextInt(); input.nextLine(); // Consume newline left-over String str1 = input.nextLine();
あるいは、入力を読み取り
Scanner.nextLine
、必要な適切な形式に変換することもできます。たとえば、次のように整数に変換できます。Integer.parseInt(String)
方法。int option = 0; try { option = Integer.parseInt(input.nextLine()); } catch (NumberFormatException e) { e.printStackTrace(); } String str1 = input.nextLine();