Home > Mobile >  Validation not working correctly with Do-While loop
Validation not working correctly with Do-While loop

Time:10-20

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

CodePudding user response:

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. Then, use a debugger (or a lot of System.out.println statements), and check that the computer does what you think it should.

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.

CodePudding user response:

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