【发布时间】:2014-06-11 22:31:45
【问题描述】:
我正在尝试定义一个要求用户输入 (x) 的主要方法。如果该值 >= 0,它会要求另一个输入 (y)。但如果该值
Scanner keyboard = new Scanner(System.in);
final int NUMBER_OF_TRIES = 3;
boolean correctNumber = false;
int attemptNumber = 0;
int x = keyboard.nextInt();
keyboard.nextLine();;
while (x < 0)
{
System.out.println("Must not be negative.");
System.out.print("Initial x: ");
int x = keyboard.nextInt(); keyboard.nextLine();
if (x >= 0)
{
correctNumber = true;
}
else
{
System.out.println("Incorrect answer");
attemptNumber++;
}
if(x < 0 && attemptNumber == NUMBER_OF_TRIES)
{
System.out.println("Too many errors. Exiting.");
break;
}
但由于我已经定义了“x”,所以我不能在循环内再次执行此操作。我认为我的问题很简单,但我无法找到解决问题的方法。有人知道怎么做吗?
【问题讨论】:
-
你的问题真的没有意义。你为什么担心重新定义“x”?问题是什么?错误信息?意外输出?
标签: java variables loops while-loop