【发布时间】:2014-07-10 12:28:23
【问题描述】:
我有以下代码,但是在第一轮循环后总是显示重复的提示。如何防止提示显示两次?
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 使用扫描仪对象有关。
【问题讨论】:
-
用调试器单步调试你的代码,它就会变得清晰。
-
@MattBall 我已经做过了,但是调试器只能显示变量的值,但不能显示存储在字符串缓冲区中的内容。 (如果我错了,请纠正我)。似乎缓冲区没有被刷新导致重复。
-
永远不要明确检查条件中的
boolean值。这是容易出错且丑陋的。if(x = true)总是true。虽然您正确使用了比较运算符,但您应该写成while(!choice.equals("exit")). -
@BoristheSpider 我已经编辑了代码,你能取消 -1 吗?
-
为什么我会因为你写的代码不好而对你投反对票?这不是反对票的目的。我没有投反对票,但我怀疑有几个人认为您的问题缺乏研究工作。