【问题标题】:How to validate user input in Java? [duplicate]如何在 Java 中验证用户输入? [复制]
【发布时间】:2022-01-16 22:25:09
【问题描述】:

我正在尝试获取用户输入并检查它是“1”还是“2”,如果不是则显示错误消息。即使输入正确,我也会不断收到错误消息。

Scanner user_input = new Scanner(System.in);
String choice = "";
// Input Validation
do {
   // Read user choice
   choice = user_input.nextLine();
            
   if (!choice.equals("1") || !choice.equals("2"))
      System.out.println("Invalid input. Give new value");
   }while (!choice.equals("1") || !choice.equals("2"));```

【问题讨论】:

  • 想一想!choice.equals("1") || !choice.equals("2") 的确切含义。当ab 都为假时,a || b 为假。你的两个 !equals 检查什么时候会是假的?
  • 其他可能使用boolean 标志来确定正确性(对于循环),您当前的方法有什么问题?
  • @tgdavies 当我输入“1”,使条件为真时,它仍然拒绝停止循环
  • @panosttm 仅供参考,验证命令行输入并不是 (IMO) 对学习时间的最佳利用。 HTML5 的输入验证确实是最先进的。现在大部分时间你很可能会在服务器端使用 Java,在那里你可以使用 400 错误来表示“输入错误”
  • 当条件为false时,循环将退出,而不是true时。

标签: java validation input


【解决方案1】:

您的情况不正确。 如果需要消除 1 和 2,请使用逻辑 AND。 我认为您想实现这一目标

       do {
            choice = user_input.nextLine();

            if (!choice.equals("1") && !choice.equals("2"))
                System.out.println("Invalid input. Give new value");
        } while (!choice.equals("1") && !choice.equals("2"));

此外,为了消除冗余并提高代码的可读性,请考虑将验证逻辑移除到单独的方法中。

public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);
        String choice = "";
        
        do {
            choice = user_input.nextLine();

            if (isValid(choice))
                System.out.println("Invalid input. Give new value");
        } while (isValid(choice));

        System.out.println("Your input is valid: " + choice);
    }
    
    private static boolean isValid(String choice) {
        return !choice.equals("1") && !choice.equals("2");
    }

【讨论】:

    【解决方案2】:

    条件中存在逻辑错误。应该有“&&”而不是“||”。

    感谢@tgdavies。

    像这样……

            String choice = "";
            // Input Validation
            do {
               // Read user choice
               choice = user_input.nextLine();
    
               if (!choice.equals("1") && !choice.equals("2"))
                  System.out.println("Invalid input. Give new value");
            }while (!choice.equals("1") && !choice.equals("2"));
    

    【讨论】:

      【解决方案3】:

      if (!choice.equals("1") || !choice.equals("2")) 没有意义

      我的头脑很简单,所以我总是喜欢做一些简单的检查,例如...

      System.out.println(!true || !false); // !"1".equals("1") || !"1".equals("2")
      System.out.println(!false || !true); // !"2".equals("1") || !"2".equals("2")
      System.out.println(!false || !false); // !"3".equals("1") || !"3".equals("2")
      

      打印出来的

      true // Show error message ... this is wrong, `1` is valid
      true // Show error message ... this is wrong, `2` is valid 
      true // Show error message ... this is correct
      

      这是明显错误的,第一条语句,我们当不是12时,打印错误信息

      因此,相反,我们应该反转|| 两边的结果,例如...

      System.out.println(!(true  || false)); // !("1".equals("1") || "1".equals("2"))
      System.out.println(!(false  || true)); // !("2".equals("1") || "2".equals("2"))
      System.out.println(!(false || false)); // !("3".equals("1") || "3".equals("2"))
      

      打印...

      false // Don't show error message ... `1` is valid
      false // Don't show error message ... `2` is valid
      true // Show error message ... `3` is invalid
      

      好吧,这似乎更好

      我还会一路简化退出条件...

      Scanner user_input = new Scanner(System.in);
      String choice = "";
      boolean isValidChoice = false;
      // Input Validation
      do {
          // Read user choice
          choice = user_input.nextLine();
      
          if (!(choice.equals("1") || choice.equals("2"))) {
              System.out.println("Invalid input. Give new value");
          } else {
              isValidChoice = true;
          }
      } while (!isValidChoice);
      System.out.println("Good choice!");
      

      【讨论】:

        【解决方案4】:

        如果输入有效,您可以在循环中间转义。

        public static void main(String[] args) {
            Scanner user_input = new Scanner(System.in);
            String choice = "";
            // Input Validation
            while (true) {
                // Read user choice
                choice = user_input.nextLine();
                if (choice.equals("1") || choice.equals("2"))
                    break;
                System.out.println("Invalid input. Give new value");
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-15
          • 1970-01-01
          • 1970-01-01
          • 2014-06-04
          • 2012-05-05
          相关资源
          最近更新 更多