我有一个用 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 运算符,但同样的问题。只接受那些特定字符的最佳方法是什么?非常感激。