【问题标题】:Need to update a variable inside a while loop需要在while循环中更新一个变量
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果退出循环的条件是输入3次负值,则将其作为实际条件。代码也应该更容易阅读。

    incorrectAttempts = 0;
    
    while (incorrectAttempts < 3)
    {
    
    get new value
    
    value invalid?
     yes: incorrectAttempts = incorrectAttempts + 1;
     no: do anything else;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2021-10-08
      • 2015-01-05
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多