【问题标题】:Enforcing valid input in Java在 Java 中强制执行有效输入
【发布时间】:2010-09-20 00:25:55
【问题描述】:

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

我最初是这样写的:

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 运算符,但同样的问题。只接受那些特定字符的最佳方式是什么? 非常感谢。

【问题讨论】:

    标签: java string validation char java.util.scanner


    【解决方案1】:

    你的逻辑不正确。您应该使用逻辑 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") &&
            ...)
    

    【讨论】:

    • 将命令转换为大写或小写可能是个好主意,因为他正在验证数据
    • 绝对有效。我之前尝试过使用 && ,但它没有用。我发现这是因为我在更改运算符后没有保存文件。非常感谢您的回答!
    • 对于不同的情况,我只是在读入字符串后使用 command.toLowerCase()。
    【解决方案2】:

    您应该将您的命令定义为常量(单独地)。像这样的硬编码值会使您以后更难更新代码。

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

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

    否则,如果这是生产代码,我会考虑制作一个简单的 Command(char) 类并提供单独的命令常量作为集合的一部分(可能是针对 Character 键的 Map),可以对其进行测试以查看是否包含匹配命令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      相关资源
      最近更新 更多