Java控制台中的重复提示
我有以下代码,但是在第一轮循环后,它总是显示重复的提示。如何防止提示显示两次Java控制台中的重复提示,java,console,prompt,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.n
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?)
继续/退出:继续
输入一个数字:3
Continue/Exit:Continue/Exit:Exit缓冲区有一个换行符,您需要刷新缓冲区。试试这个:
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
nextInt()。当您下次使用nextLine
时,会读取该值,导致程序不等待用户输入。您需要执行以下任一操作:
number = scn.nextInt();
scn.nextLine(); //advance past newline
或者这个:
number = Integer.parseInt(scn.nextLine()); //read whole line and parse as int
阅读中的nextInt
和nextLine
。您可以使用:-
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"));
}
使用调试器逐步检查代码,代码就会变得清晰。@MattBall我已经这样做了,但调试器只能显示变量的值,而不能显示存储在字符串缓冲区中的内容。(如果我错了,请纠正我)。缓冲区似乎没有被清除,导致重复。永远不要明确检查条件中的布尔值。这很容易出错,而且很难看<代码>如果(x=true)
总是true
。在正确使用比较运算符的同时,您应该编写,而(!choice.equals(“exit”))
@borisspider我已经编辑了代码,您能取消-1吗?为什么我会因为您编写了错误的代码而否决您?这不是反对票的目的。我没有投反对票,但我怀疑有几个人认为你的问题缺乏研究努力。-1因为为每次迭代创建一个新的扫描仪是不好的做法,而且有更干净的方法来解决这个问题。也没有解释为什么会发生这种情况。@kviirinextLine()
读取int并不是更好的选择。“为什么这是不好的做法?”彼得拉德,对一个人来说是不必要的垃圾。另外,读取一行更好,因为这是用户在这里想要做的-读取一行并将其视为int。不需要@kviiri扫描器?这个答案不信任输入值。@彼得,是的,每次迭代都不需要扫描仪。您只需要一个Scanner对象,不需要为每次迭代创建一个新的Scanner对象。不建议使用仅代码的答案,因为它们没有帮助。OP遇到了什么问题?怎么能修好呢?这些问题只能通过逐行比较来回答。因此,我认为这个回答对他没有帮助。