2010-09-20 54 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(); 
} 

否则,如果这是生产代码,我会考虑一个简单的命令(炭)班,并提供个人命令常量部分(可能是一个映射到字符键的映射),可以测试它是否包含匹配的命令。