2010-09-20 82 views
0

我有一個用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運算符,但同樣的問題。接受這些特定人物的最佳方式是什麼? 非常感謝。

回答

2

您的邏輯錯誤。你應該使用邏輯AND而不是OR。另外我相信你想用charAt()代替substring()然後比較字符。

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

否則,如果你想測試的實際單字符字符串輸入,只需要檢查使用的字符串相等。

while( !command.equals("e") && 
     !command.equals("c") && 
     !command.equals("s") && 
     ...) 
+0

自從他驗證數據後,將命令轉換爲大寫或小寫可能是一個好主意 – 2010-09-20 00:40:00

+0

絕對有效。我早些時候嘗試過使用&&,但它不起作用。我發現這是因爲我在更改操作符後沒有保存文件。非常感謝你的回答! – Seephor 2010-09-20 00:42:06

+0

對於不同的情況,我只是在讀取字符串後使用command.toLowerCase()。 – Seephor 2010-09-20 00:44:50

0

您應該將您的命令定義爲常量(單獨)。像這樣的硬編碼值使得將來更新代碼變得更加困難。

如果程序是簡單的概念或家庭作業的證據,我會用:

private static final String COMMANDS = "ecsrludkftpmq"; 

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

否則,如果這是生產代碼,我會考慮一個簡單的命令(炭)班,並提供個人命令常量部分(可能是一個映射到字符鍵的映射),可以測試它是否包含匹配的命令。