Java 需要更新while循环中的变量
我试图定义一个主方法,它要求用户输入(x)。如果该值>=0,则要求另一个输入(y)。但是如果值小于0,玩家有三次机会输入正确的值,否则他退出游戏。这就是我到目前为止所拥有的:Java 需要更新while循环中的变量,java,variables,loops,while-loop,Java,Variables,Loops,While Loop,我试图定义一个主方法,它要求用户输入(x)。如果该值>=0,则要求另一个输入(y)。但是如果值小于0,玩家有三次机会输入正确的值,否则他退出游戏。这就是我到目前为止所拥有的: Scanner keyboard = new Scanner(System.in); final int NUMBER_OF_TRIES = 3; boolean correctNumber = false; int attemptNumber = 0; int x = keyboard.nextInt(); keyboa
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;
}
扫描仪键盘=新扫描仪(System.in);
最后的整数次尝试=3;
布尔值=假;
int attemptNumber=0;
int x=keyboard.nextInt();
键盘。nextLine();;
而(x<0)
{
System.out.println(“不得为负数”);
系统输出打印(“首字母x:”);
int x=keyboard.nextInt();keyboard.nextLine();
如果(x>=0)
{
正确数字=真;
}
其他的
{
System.out.println(“回答不正确”);
attemptNumber++;
}
if(x<0&&attemptNumber==尝试次数)
{
System.out.println(“错误太多,正在退出”);
打破
}
但由于我已经定义了“x”,我不能在循环中再次这样做。我认为我的问题很简单,但我无法找到解决方法。有人知道如何解决吗?如果退出循环的条件是输入负值3次,则将其用作实际条件。代码也应该更易于阅读
incorrectAttempts = 0;
while (incorrectAttempts < 3)
{
get new value
value invalid?
yes: incorrectAttempts = incorrectAttempts + 1;
no: do anything else;
}
incorrecttempts=0;
而(不正确的<3)
{
获得新的价值
值无效?
是:不正确提示=不正确提示+1;
不:做任何其他事情;
}
如果您只是从第12行中删除“int”,看起来这可能会起作用。您不需要在那里声明变量,因为您已经声明了它。您的问题没有真正意义。为什么您担心重新定义“x”?问题是什么?错误消息?意外输出?