Java控制台中的重复提示

use*_*460 -2 java console prompt

我有以下代码,但在第一轮循环后它始终显示重复的提示.如何防止提示显示两次?

public static void main(String[] args) 
{
    Scanner scn = new Scanner(System.in);
    int number = 0;
    String choice = "";

    do
    {
        System.out.print("Continue / Exit: ");
        choice = scn.nextLine().toLowerCase();

        if (choice.equals("continue"))
        {
            System.out.print("Enter a number: ");
            number = scn.nextInt();
        }   
    }while(!choice.equals("exit")); 

}
Run Code Online (Sandbox Code Playgroud)

节目输出:

Continue / Exit: continue
Enter a number: 3
Continue / Exit: Continue / Exit: exit    <--- Duplicated prompt here (how to remove the duplicate?)
Run Code Online (Sandbox Code Playgroud)

我怀疑它是与扫描仪对象为使用stringint.

kvi*_*iri 5

nextInt()不会读取换行符,因此您最终会在Scanner缓冲区中显示一个空行(只是int之后的换行符).下次使用时会读取此内容nextLine,导致程序无法等待用户输入.你需要这样做:

number = scn.nextInt();
scn.nextLine(); //advance past newline
Run Code Online (Sandbox Code Playgroud)

或这个:

number = Integer.parseInt(scn.nextLine()); //read whole line and parse as int
Run Code Online (Sandbox Code Playgroud)

阅读nextIntnextLine的Java文档.