Reputation: 159
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
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
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
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
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