Peter Bucher
Peter Bucher

Reputation: 49

Verifying strings Java

do {
            grade[y] = JOptionPane.showInputDialog(null, "For student #" + inputGrades.students + " enter grade for course #" + classes);
            if (!grade[y].equals("A") || !grade[y].equals("B") || !grade[y].equals("C") || !grade[y].equals("D") || !grade[y].equals("F")) {
                grade[y] = JOptionPane.showInputDialog(null, "For student #" + inputGrades.students + " enter grade for course #" + classes);
            } else {
                validgrade = true;
            }
        } while (!validgrade);

I'm trying to make a sure a sting equals either A, B, C, D, or F. I get stuck in an infinite loop. Why?

Upvotes: 0

Views: 39

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

This condition is always true:

if (!grade[y].equals("A") || !grade[y].equals("B") || !grade[y].equals("C") || !grade[y].equals("D") || !grade[y].equals("F"))

grade[y] cannot equal A, B, C, D, and F at the same time. At most one !equals(...) will be false. The remaining four would be true, turning the results of OR into true as well.

You need && instead of ||:

if (!grade[y].equals("A") && !grade[y].equals("B") && !grade[y].equals("C") && !grade[y].equals("D") && !grade[y].equals("F"))

In addition, it is not necessary to call JOptionPane.showInputDialog inside the if conditional. All you need to do is letting the loop continue. So the simplified code could look like this:

do {
    grade[y] = JOptionPane.showInputDialog(null, "For student #" + inputGrades.students + " enter grade for course #" + classes);
} while (!grade[y].equals("A") && !grade[y].equals("B") && !grade[y].equals("C") && !grade[y].equals("D") && !grade[y].equals("F"));

Upvotes: 5

Related Questions