【问题标题】:Java: do/while loop repeating even though condition has been metJava:即使满足条件,do/while 循环也会重复
【发布时间】:2013-03-19 18:23:00
【问题描述】:

我正在尝试一个简单的 do while 循环,假设在输入小于 1 且大于 1000 时运行。它应该要求用户输入正确的数字,否则在循环中。它现在似乎正在做的是再重复一次循环,要求正确的输入,然后显示结束消息。如果满足条件,不确定为什么会重复它

String name = JOptionPane.showInputDialog(null,
        "Please enter students lastname");

int input = Integer.parseInt(JOptionPane.showInputDialog(null,
        "Please enter students ID"));

do {
    JOptionPane.showMessageDialog(null,
            "Please enter a student ID within the correct parameters");
    input = Integer.parseInt(JOptionPane.showInputDialog(null,
            "Please enter students ID"));
} while (input < 1 && input > 1000);

// Output dialog with user input
JOptionPane.showMessageDialog(null, "StudentID: " + input
        + "\nStudent Last: " + name);

【问题讨论】:

  • 你能提供一个小于 1 且大于 1000 的数字的例子吗?
  • 你明白 do-while 执行 before 检查条件,对吗?所以它会一直运行到 input==1002
  • (input &lt; 1 &amp;&amp; input &gt; 1000) 永远不会是真的!
  • 条件应该是(input &lt; 1 || input &gt; 1000),接受1到1000之间的数字,对吧?

标签: java do-while


【解决方案1】:

您至少要展示两次对话框——一次在循环之前,一次在循环内。

do-while 直到循环至少执行一次后才测试条件。

你可以:

  • 取消第一次调用以显示输入对话框。
  • 或者将您的 do-while 循环更改为 while 循环。

此外,请参阅@GrailsGuy 的关于循环测试的 cmets。您当前的测试将始终失败。

【讨论】:

    【解决方案2】:

    我认为您虽然 CONDITION 不正确,因为我在打印语句中阅读 cmets 我相信您需要

     while (input > 1 && input < 1000);
    

    因为ID不能是负数。

    请记住,如果 ID 值介于 2 to 999 之间,则此条件为真。

    正如您评论的那样澄清一下,如果用户输入的数字超出范围 (1-1000),即2005,我希望循环循环,要求用户输入范围内的数字,直到满足该条件

    喜欢,阅读 cmets 以了解我的代码是什么:

    input = -1;
    while(input < 1 || input > 1000){ 
    //    ^              ^ OR greater then 1000
    // either small then 1   
    }
    

    注意:我选择了 OR 而不是 AND,因为任一条件失败,您的循环都应该继续。

    【讨论】:

    • 只是为了澄清,如果用户输入的数字超出范围(1-1000),即2005,我希望循环循环,要求用户输入范围内的数字,直到满足该条件。
    • @user1901231 我的答案只是基于提供的信息+我能理解的猜测答案。让我看看我是不是错了
    【解决方案3】:

    我会用 while 更改它:

    int input = Integer.parseInt(JOptionPane.showInputDialog(null,
        "Please enter students ID"));
    while(input < 1 || input > 1000) {
        // Your stuff
    }
    

    解释

    我认为错误的是,首先,任何数字都不可能(同时)小于 1 和大于 1000,所以很明显,有效输入应该在 outside 指定范围(即从-Infinity0 OR1001Infinity)。

    其次,另一个答案中提到的内容:do...while 循环始终至少运行一次,并且只要while 条件为真,它就会重复。由于输入是在进入循环之前被读取的,'confirmationalways takes place... What's the need to request a correction on a possibly correctinput` 的值?

    我认为错误的是对验证规则含义的误解:

    我正在尝试一个简单的 do while 循环,假设输入小于 1,并且大于 1000

    这个词是什么意思?我认为这意味着输入必须在给定范围之外

    【讨论】:

    • 谢谢巴兰卡。做到了!
    • 不知道为什么这被标记为答案,因为它不是第一个答案并且没有解释什么是真正的错误。
    • @Colleen 我已经编辑了我的答案,解释了我认为错的地方。顺便说一句,接受的答案“并不意味着它是最佳答案,它只是意味着它对提出问题的人有效”(来自 关于 页面:stackoverflow.com/about
    猜你喜欢
    • 2013-04-08
    • 2012-10-01
    • 2022-10-13
    • 2016-03-14
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多