代码之家  ›  专栏  ›  技术社区  ›  Seephor

在Java中执行有效输入

  •  0
  • Seephor  · 技术社区  · 14 年前

    我有一个用Java编写的类,其中的一个方法是GET命令() 此方法的目的是读取字符串,并查看用户键入的内容与任何可接受的命令匹配。

    我最初就是这样写的:

    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;
    
    }
    

    现在,我看到了这个问题,因为我使用了“或”操作符,所以它不会逃离那个循环,因为我输入的字符总是不等于它们中的一个。我试着把它改成和运算符,但同样的问题。只接受这些特定字符的最佳方法是什么? 非常感谢。

    2 回复  |  直到 13 年前
        1
  •  2
  •   Jeff Mercado    14 年前

    你的逻辑不正确。您应该使用逻辑和而不是ORS。我也相信你想用 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") &&
            ...)
    
        2
  •  0
  •   Syntax    14 年前

    您应该将命令定义为常量(单独)。这样的硬编码值使得将来更新代码更加困难。

    如果程序只是概念或家庭作业的证明,我会使用:

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

    否则,如果这是生产代码,我将考虑创建一个简单的命令(char)类,并提供单独的命令常量作为集合的一部分(可能是针对字符键的映射),可以测试它是否包含匹配的命令。