Nei Mina
Nei Mina

Reputation: 159

Do while loop that runs as long as user input isn't equal to certain words NOT working?

I don't understand why this isn't working. The program always reprompts me no matter what I type in even if it is a valid action word.

String action = "";
        do {
        System.out.print("Enter what you want to do (ADD, REMOVE, "
                   + "LIST, SAVE, SORT): ");
        action = keyboard.next();
        } while ((!(action.equalsIgnoreCase("ADD")) 
                || !(action.equalsIgnoreCase("REMOVE")) 
                || !(action.equalsIgnoreCase("LIST")) 
                || !(action.equalsIgnoreCase("SAVE")) 
                || !(action.equalsIgnoreCase("SORT"))));

Upvotes: 0

Views: 432

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Correct. You used or, but you wanted and.

((!(action.equalsIgnoreCase("ADD")) 
            && !(action.equalsIgnoreCase("REMOVE")) 
            && !(action.equalsIgnoreCase("LIST")) 
            && !(action.equalsIgnoreCase("SAVE")) 
            && !(action.equalsIgnoreCase("SORT"))));

Every word will satisfy the test not ADD or not REMOVE. You might apply De Morgan's Laws like,

(!(action.equalsIgnoreCase("ADD")  
        || action.equalsIgnoreCase("REMOVE") 
        || action.equalsIgnoreCase("LIST") 
        || action.equalsIgnoreCase("SAVE") 
        || action.equalsIgnoreCase("SORT")))

Upvotes: 2

kriyeta
kriyeta

Reputation: 705

try this

String action = "";
    do {
    System.out.print("Enter what you want to do (ADD, REMOVE, "
               + "LIST, SAVE, SORT): ");
    action = keyboard.next();
    } while (!((action.equalsIgnoreCase("ADD")) 
            || (action.equalsIgnoreCase("REMOVE")) 
            || (action.equalsIgnoreCase("LIST")) 
            || (action.equalsIgnoreCase("SAVE")) 
            || (action.equalsIgnoreCase("SORT"))));

Upvotes: 0

Eran
Eran

Reputation: 393831

Your condition is wrong. You should terminate the loop if action isn't equals to any of the valid action words, but your condition continues the loop as long as action isn't equal to at least one of the valid actions, which is always true (since valid can only be equal to at most one valid action at a time).

The correct condition should be :

    } while ((!(action.equalsIgnoreCase("ADD")) 
            && !(action.equalsIgnoreCase("REMOVE")) 
            && !(action.equalsIgnoreCase("LIST")) 
            && !(action.equalsIgnoreCase("SAVE")) 
            && !(action.equalsIgnoreCase("SORT"))));

Upvotes: 0

khelwood
khelwood

Reputation: 59113

Your combined while condition is always true. If !(action.equalsIgnoreCase("ADD") is false, then your action string must be "ADD". So all the other conditions will be true. So the whole condition is true.

Replace your || with &&.

Alternatively, put your words in a List or other container and test

while (!words.contains(action))

Upvotes: 0

Related Questions