0

我有一个用 Java 编写的类,其中一个方法是 getCommand() 该方法的目的是读取字符串并查看用户输入的内容与任何可接受的命令匹配。

我最初是这样写的:

public char getCommand(){


    System.out.println("Input command: ");
     command = input.nextLine();

    while(command.length() != 1){
        System.out.println("Please re-enter input as one character: ");
        command = input.nextLine();
    }

    while(  command.substring(0) != "e" ||
            command.substring(0) != "c" || 
            command.substring(0) != "s" ||
            command.substring(0) != "r" ||
            command.substring(0) != "l" ||
            command.substring(0) != "u" ||
            command.substring(0) != "d" ||
            command.substring(0) != "k" ||
            command.substring(0) != "f" ||
            command.substring(0) != "t" ||
            command.substring(0) != "p" ||
            command.substring(0) != "m" ||
            command.substring(0) != "q"){
        System.out.println("Please enter a valid character: ");
        command = input.nextLine();
    }

    fCommand = command.charAt(0);

    return fCommand;

}

现在,我看到问题在于,由于我使用 OR 运算符,它不会逃脱该循环,因为我输入的字符将始终不等于其中之一。我尝试将其更改为 AND 运算符,但同样的问题。只接受那些特定字符的最佳方法是什么?非常感激。

4

2 回答 2

2

你的逻辑不正确。您应该使用逻辑 AND 而不是 OR。另外我相信你想使用charAt()而不是substring()比较字符。

IE,

while(  command.charAt(0) != 'e' &&
        command.charAt(0) != 'c' && 
        command.charAt(0) != 's' &&
        ...)

否则,如果您想测试实际的单字符字符串输入,只需使用字符串相等性进行检查。

while(  !command.equals("e") &&
        !command.equals("c") &&
        !command.equals("s") &&
        ...)
于 2010-09-20T00:35:12.187 回答
0

您应该将命令定义为常量(单独)。像这样的硬编码值会使将来更新代码变得更加困难。

如果该程序只是概念证明或作业,我会使用:

private static final String COMMANDS = "ecsrludkftpmq";

while(!COMMANDS.contains(command.getChar(0)) {
  System.out.println("Please enter a valid character: ");
  command = input.nextLine();
}

否则,如果这是生产代码,我会考虑制作一个简单的 Command(char) 类并提供单独的命令常量作为集合的一部分(可能是针对 Character 键的 Map),可以对其进行测试以查看是否包含匹配的命令。

于 2010-09-20T00:47:55.533 回答