【问题标题】:How can I set limits on how many characters can be inputted? (Java)如何设置可以输入多少个字符的限制? (爪哇)
【发布时间】:2025-11-23 02:35:01
【问题描述】:
do{
        out.println("\n---------------------------------");
        out.println("---------------------------------");
        out.print("Please type your acces card number: ");

    try{
        card = input.nextInt();

        if(card.length != 10){
            out.println("The number you typed is incorrect");
            out.println("The number must be 10 numbers long");
        continue;
            }
        }   

        catch(InputMismatchException ex){
            }
    }while(true);    

我正在尝试使卡片长度为 10 个字符。与 (1234567890) 类似,如果用户输入 (123) 或 (123456789098723),则会出现错误消息。 card.length 似乎不起作用。

【问题讨论】:

  • 也许您可以先尝试接收纯字符串,然后将其解析为整数。
  • 我支持“将卡号视为字符串”的方法 - 通常卡号不需要对其执行数学运算,adn 可以包含前导零,因此使用字符串实际上是明智的代表。

标签: java


【解决方案1】:

只需将 int 更改为 String

   String card = input.next();
   if(card.length() != 10){
      //Do something
   }

您可以稍后轻松地将其转换为 int

   int value = Integer.parseInt(card);

【讨论】:

    【解决方案2】:

    你可以改变

    if(card.length != 10){
    

    类似

    if(Integer.toString(card).length() != 10){
    

    当然,有可能是用户输入的

    0000000001
    

    1 相同。你可以试试

    String card = input.next(); // <-- as a String
    

    然后

    if (card.length() == 10)
    

    最后

    Integer.parseInt(card)
    

    【讨论】:

      【解决方案3】:

      在 Java 中,您无法获得 intlength。查找位数的最简单方法是将其转换为String。但是,您也可以做一些数学运算来找出数字的长度。您可以找到更多信息here

      【讨论】:

        【解决方案4】:

        您无法获得int 的长度。如果需要,最好以String 的形式获取输入,然后将其转换为 int。您可以在 while 循环中进行错误检查,如果您喜欢短路,也可以让 while 检查显示您的错误消息:

        out.println("\n---------------------------------");
        out.println("---------------------------------");
        out.print("Please type your access card number: ");
        
        do {
            try {
                card = input.nextLine();
            } catch (InputMismatchException ex) {
                continue;
            }
        } while ( card.length() != 10 && errorMessage());
        

        并让您的errorMessage 函数返回 true,并显示错误消息:

        private boolean errorMessage()
        {
            out.println("The number you typed is incorrect");
            out.println("The number must be 10 numbers long");
            return true;
        }
        

        【讨论】:

          最近更新 更多