我不明白为什么这不起作用。即使它是一个有效的动作词,无论我输入什么,该程序总是会重新命令我。
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"))));
答案 0 :(得分:2)
正确。你用过或者,但是你想要和。
((!(action.equalsIgnoreCase("ADD"))
&& !(action.equalsIgnoreCase("REMOVE"))
&& !(action.equalsIgnoreCase("LIST"))
&& !(action.equalsIgnoreCase("SAVE"))
&& !(action.equalsIgnoreCase("SORT"))));
每个单词都会满足测试而不是ADD或不是REMOVE。您可以申请De Morgan's Laws之类的,
(!(action.equalsIgnoreCase("ADD")
|| action.equalsIgnoreCase("REMOVE")
|| action.equalsIgnoreCase("LIST")
|| action.equalsIgnoreCase("SAVE")
|| action.equalsIgnoreCase("SORT")))
答案 1 :(得分:0)
您的合并while
条件始终为true
。如果!(action.equalsIgnoreCase("ADD")
为false
,那么您的action
字符串必须为"ADD"
。所以其他所有条件都是true
。所以整个条件是true
。
将||
替换为&&
。
或者,将您的文字放在List
或其他容器中并进行测试
while (!words.contains(action))
答案 2 :(得分:0)
你的病情有误。如果action
不等于任何有效的操作词,则应终止循环,但只要action
不等于至少其中一个,您的条件就会继续循环有效的操作,始终为真(因为有效操作一次最多只能等于一个有效操作)。
正确的条件应该是:
} while ((!(action.equalsIgnoreCase("ADD"))
&& !(action.equalsIgnoreCase("REMOVE"))
&& !(action.equalsIgnoreCase("LIST"))
&& !(action.equalsIgnoreCase("SAVE"))
&& !(action.equalsIgnoreCase("SORT"))));
答案 3 :(得分:0)
试试这个
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"))));