简体   繁体   English

使用 Do-While 循环验证无法正常工作

[英]Validation not working correctly with Do-While loop

I have set the code correctly no errors but it seems there is because even if I enter integers higher than the limit for the program it still continues to the next line |我已经正确设置了代码没有错误,但似乎是因为即使我输入的整数高于程序的限制,它仍然会继续到下一行 | Here is the code for better understanding:这是为了更好地理解的代码:

    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);

You're saying: Loop while grade is between 65 and 99. Just read your own code, and if that's not helping, step through it, use pen and paper if you have to, and figure out what you think the code should do.你是说:当成绩在 65 到 99 之间时循环。只要阅读你自己的代码,如果这没有帮助,请逐步完成,如果需要,使用笔和纸,并弄清楚你认为代码应该做什么。 Then, use a debugger (or a lot of System.out.println statements), and check that the computer does what you think it should.然后,使用调试器(或大量System.out.println 语句),并检查计算机是否按照您的想法运行。

There where you two are in disagreement, you found the bug.在你们两个有分歧的地方,你发现了错误。

That process would have trivially found this bug.这个过程很容易发现这个错误。

Now you know what to do next time.现在你知道下次该做什么了。

HERE IS THE SOLUTION:这是解决方案:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM