我有一個用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