我有以下代码,但在第一轮循环后它始终显示重复的提示。如何阻止提示显示两次?
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?)
我怀疑它与使用string
和int
的扫描仪对象有关。
答案 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中的nextInt
和nextLine
。
答案 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