【问题标题】:How to count only 4 integers from an input - JAVA如何从输入中仅计算 4 个整数 - JAVA
【发布时间】:2020-06-15 09:18:14
【问题描述】:

嘿,刚刚为学校做一个项目,想知道如何限制用户只能输入 4 整数输入作为邮政编码。例如:(1454)

    while (count == 1)
    {
        System.out.println("Input a postcode for us to send you the package: ");
        try
        {
            postage = in.nextInt();
        }
        catch (Exception e)
        {
            System.out.println("This is an invalid input!");
            in.next();
            continue;
        }
        if (postage >= 0000 && postage <= 9999)
        {
            System.out.println(" ");
        }
    }

【问题讨论】:

  • 你应该阅读输入,如果太长,再问一遍?

标签: java validation input integer


【解决方案1】:

一种方法是将输入作为字符串,然后仅将前四个字符转换为 int(parseInt()) 并使用它。

【讨论】:

    【解决方案2】:

    您可以使用 String.matches(String regex) 方法和正则表达式 \\d{4} 来检查输入是否为 4 位:

    // ---
    if(String.valueOf(postage).matches("\\d{4}")) {
        System.out.println(" ");
    }
    // ---
    

    关于正则表达式:

    • \\d:数字
    • {4}:匹配4位数字

    【讨论】:

      【解决方案3】:

      你可以使用while:

      while(!(postage >= 0000 && postage <= 9999)){
           System.out.println("This is an invalid input!");
           postage = in.nextInt();
      }
      

      【讨论】:

      • 这将导致无限循环。您需要更新循环内的变量。
      猜你喜欢
      • 2017-02-09
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多