【问题标题】:Validation not working correctly with Do-While loop验证无法在 Do-While 循环中正常工作
【发布时间】:2021-12-06 21:02:58
【问题描述】:

我已经正确设置了代码,没有错误,但似乎是因为即使我输入的整数高于程序的限制,它仍然会继续到下一行 | 这是更好理解的代码:

    do {
        System.out.print("Enter the grade of the student for the subject " + counter + ": ");
        grade = Integer.parseInt(kbd.nextLine());
        if (grade < 65) {
            System.out.println("Grades Range only from 65-99!");
        }
        if (grade > 99) {
            System.out.println("Grades Range only from 65-99!");
        }
    } while (grade > 65 && grade < 99);
    do {
        System.out.print("Enter the number of units for the subject " + counter + ": ");
        units = Integer.parseInt(kbd.nextLine());
        if (units < 1) {
            System.out.println("Units Range only from 1-12!");
        }
        if (units > 12) {
            System.out.println("Units Range only from 1-12!");
        }
    } while (units > 1 && units < 12);

【问题讨论】:

  • 所以如果你输入200 那么(grade &gt; 65 &amp;&amp; grade &lt; 99) 是假的
  • 是的,它将循环直到用户输入该范围内的整数
  • 不,while 不正确,它不会循环
  • 你想说loop while number小于65或大于99
  • 我该如何改变它

标签: java loops validation do-while


【解决方案1】:

您的意思是:在 65 到 99 之间循环。只需阅读您自己的代码,如果没有帮助,请逐步执行,必要时使用笔和纸,并弄清楚您对代码的看法应该做。然后,使用调试器(或 很多 System.out.println 语句),并检查计算机是否按照您的想法进行。

在你们两个有分歧的地方,你发现了错误。

这个过程会很容易发现这个错误。

现在你知道下次该做什么了。

【讨论】:

  • 感谢您的建议我会永远记住这一点:>
【解决方案2】:

这是解决方案:

      BEFORE: while (grade > 65 && grade < 99);
      AFTER: while (grade < 65 || grade > 99);

      BEFORE: (units > 1 && units < 12);
      AFTER: (units < 1 || units > 12);

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 2015-01-06
    • 1970-01-01
    相关资源
    最近更新 更多