【问题标题】:the function doesn't take more than 10 letters on scanner该功能在扫描仪上不超过 10 个字母
【发布时间】:2021-06-15 11:50:32
【问题描述】:

我需要从用户那里获取数组的长度和值,并返回显示次数最多的数字。例如:用户给了我长度“4”和数字 {83,238,8,54} 函数将返回“显示次数最多的数字是 8”; 但如果用户输入的数字通常超过 10 位,它会发送错误消息。

        String sum = "";
        
            // get the length 
                  System.out.println("Enter the size of the array :");
                  int size = in.nextInt();
             // create the array 
                  String[] arr = new String[size+1];
                  
             // get value 
                  System.out.println("Enter the elements of the array:(max capity 10 digits) ");
                  for(int i=0; i<arr.length; i++) {
                     arr[i] = in.nextLine();
                     sum+=arr[i];
                    
                  }
             
                      
                System.out.println("the numbers that you gave me are: "+sum);   
                int all = Integer.parseInt(sum);  
                
                System.out.println("the digit that shows the most time is: "+maxOccurring(all));
                  
    }

        static int countOccurrences(int x,int d) {

            int count = 0;
            while (x > 0)
            {

                if (x % 10 == d)
                count++;
                x = x / 10;
            }
            return count;
        }
         

        static int maxOccurring( int x)
        {
             

        if (x < 0)
            x = -x;

        int result = 0;

        int max_count = 1;

        for (int d = 0; d <= 10; d++)
        {

            int count = countOccurrences(x, d);
         
           
            if (count >= max_count)
            {
                max_count = count;
                result = d;
            }
        }
        return result;
        

    }
    }
    ```

【问题讨论】:

标签: java java.util.scanner digits


【解决方案1】:

您会在以下行获得NumberFormatException

int all = Integer.parseInt(sum);

异常跟踪是:

Exception in thread "main" java.lang.NumberFormatException: For input string: "25445648942"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at scan.ScannerTest.main(ScannerTest.java:27)

此异常告诉您Integer.parseInt 无法解释您通过它传递的数字(通过连接所有输入的数字获得),在这个精确的示例中:“25445648942”

这是因为此函数试图从所有这些数字中生成 Integer,其最大容量为 2^31 - 1 = 2,147,483,647。输入的数字比这个大,所以它在逻辑上失败了。

您应该分别处理每个输入的数字并计算每个数字中的数字,然后将所有数字相加得到答案。

顺便说一句,您不需要转换为数字类型来计算数字。就是简单的字符串处理

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多