Java控制台中的重复提示

时间:2014-07-10 12:28:23

标签: 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")); 

}

节目输出:

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

我怀疑它与使用stringint的扫描仪对象有关。

3 个答案:

答案 0 :(得分:5)

nextInt()没有读取换行符,所以你在Scanner缓冲区中找到一个空行(只是int之后的换行符)。下次使用nextLine时会读取此内容,导致程序无法等待用户输入。你需要这样做:

number = scn.nextInt();
scn.nextLine(); //advance past newline

或者这个:

number = Integer.parseInt(scn.nextLine()); //read whole line and parse as int

了解the Java docs中的nextIntnextLine

答案 1 :(得分:-1)

你可以使用它: -

  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 = Integer.parseInt(scn.nextLine()); 
    }
  }while(!choice.equals("exit"));

  }

答案 2 :(得分:-2)

缓冲区有换行符,需要刷新缓冲区。试试这个:

public static void main(String[] args)
{
    int number = 0;
    String choice;

    do
    {
        Scanner scn = new Scanner(System.in);
        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") == false); 

}

输出是:

Continue / Exit: continue
Enter a number: 2
Continue / Exit: continue
Enter a number: 4
Continue / Exit: exit