なぜプログラムは、ユーザからの入力を取得しないのですか?

エヴァン趙:

私は、Javaに新しいですし、私は推測ゲームを作るしようとしています。私の1行のコードでは、私は、ユーザーからの入力を取得してみてください。プログラムは、コード行を実行しなかったようにしかし、それはそうです。なぜそれが起こったのか?問題は、私の主な方法で発生しました:

Scanner input = new Scanner(System.in);

System.out.println("Let's play a guessing game!");
while (true){
    // get a random number from 1 to 10
    int random = (int) (Math.random() * 10) + 1;
    System.out.println("I am thinking of a number between 1 and 10.");
    System.out.print("What do you think it is? ");
    int guess = input.nextInt();
    System.out.println((guess == random) ? "You are correct!":"You're wrong! The number was " + random);
    System.out.print("Play again? (Y/N)");

    // this line is where the problem occurred.
    String play = input.nextLine();
    if (play.equalsIgnoreCase("N"))
        break;
}

数を推測した後、プログラムは、ちょうど彼らが再びプレイしたい場合には、ユーザーに尋ねた行を無視しました。なぜそれが起こっているのでしょうか?

ハビエル・オルティス・シルバ:

Scanner.nextInt方法は読まない改行あなたは「Enter」キーを押すと、したがって、文字をScanner.nextLineその読んだ後、右を返す改行を

あなたが使用している場合、同じことが起こるScanner.nextLine任意の後Scanner.next*を除いて、nextLine自分自身。それを解決するには、呼び出すことができScanner.nextLine、それぞれの後にScanner.nextInt保留消費するように改行を

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=362449&siteId=1