只要用户输入不等于某些单词不工作,while循环运行吗?

时间:2014-11-16 19:01:20

标签: java netbeans

我不明白为什么这不起作用。即使它是一个有效的动作词,无论我输入什么,该程序总是会重新命令我。

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

4 个答案:

答案 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"))));