スキャナは next() または nextFoo() を使用した後に nextLine() をスキップしますか? 質問する

スキャナは next() または nextFoo() を使用した後に nextLine() をスキップしますか? 質問する

入力の読み取りには メソッドと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.nextLineScanner.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();
    

おすすめ記事