java - 需要在 while 循环内更新变量

标签 java variables loops while-loop

我正在尝试定义一个主要方法,要求用户输入(x)。如果该值 >= 0,则要求另一个输入 (y)。但如果该值 < 0,则玩家有 3 次机会输入正确的值,否则他将退出游戏。这是我到目前为止所拥有的:

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”,所以我无法在循环内再次执行此操作。我认为我的问题非常简单,但我无法找到解决方法。有谁知道怎么做吗?

最佳答案

看起来如果您只是从第 12 行删除“int”,这可能会起作用。您不需要在那里声明该变量,因为您已经声明了它。

关于java - 需要在 while 循环内更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306176/

相关文章:

python - 在 Python 中创建 HDF5 数据集时如何处理可变大小的数组?

Python/MySQL "Insert into"带变量

java - Java 中监控网络适配器的轻量级方法是什么?

java - 在libgdx中绘制大背景

java - 如何查找分数数组中每个分数是否等于或低于其前面的分数?

java - 快速排序中使用的异常查找和 while 循环 (Java)

javascript - JS/Jquery 和 firebase 登录页面问题

java - 访问限制 : Is not accessible due to restriction on required library . .\jre\lib\rt.jar

c - 为什么我的案例给出错误?为什么我不能将变量放入 switch 案例中?

r - 如何在函数和循环中使用 data.table?