我有一个用Java编写的类,其中一个方法是getCommand() 该方法的目的是读入一个字符串,并查看用户键入的内容是否与任何可接受的命令。在Java中强制输入有效
这是我写的最初:
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运算符,但同样的问题。接受这些特定人物的最佳方式是什么? 非常感谢。
自从他验证数据后,将命令转换为大写或小写可能是一个好主意 – 2010-09-20 00:40:00
绝对有效。我早些时候尝试过使用&&,但它不起作用。我发现这是因为我在更改操作符后没有保存文件。非常感谢你的回答! – Seephor 2010-09-20 00:42:06
对于不同的情况,我只是在读取字符串后使用command.toLowerCase()。 – Seephor 2010-09-20 00:44:50