gpt4 book ai didi

JAVA : "java.util.InputMismatchException" error

转载 作者:行者123 更新时间:2023-12-02 04:05:16 25 4
gpt4 key购买 nike

这里是新程序员,只是想完成我的编程作业(本学期的最后一个)!

基本上,赋值如下:编写一个程序来读取整数,找到其中最大的一个,并计算它的出现次数。假设输入以0结尾。

我的代码: 导入java.util.Scanner;

public class IntCount {
public static void main(String[] args) {
int max;
int count = 1;
int num;
int test = 1;

Scanner scan = new Scanner(System.in);

System.out.println("Please enter integers");
num = scan.nextInt();

String[] testNums = Integer.toString(num).split("");

max = Integer.parseInt(testNums[0]);
System.out.println("TEST MAX = " + max);
int leng = testNums.length;

while (leng != 1) {

if ((Integer.parseInt(testNums[test])) == max) {
count++;

}

if ((Integer.parseInt(testNums[test])) > max) {
max = Integer.parseInt(testNums[test]);
}

leng = leng - 1;
test = test + 1;

}

System.out.println(java.util.Arrays.toString(testNums));

if (leng == 1) {
System.out.println("Your max number is: " + max);
System.out.println("The occurances of your max is: " +count);
} else {
System.out.println("Your max number is: " + max);
System.out.println("The occurrences of your max is: " + count);
}

}
}

代码对于以下输入可以正常工作:3525550(最大数量为 5,出现次数为 4)

代码不适用于以下输入:36542454550对于此输入,我收到以下错误:线程“main”中的异常 java.util.InputMismatchException:对于输入字符串:“36542454550” 在 java.util.Scanner.nextInt(来源未知) 在 java.util.Scanner.nextInt(来源未知) 在 IntCount.main(IntCount.java:13)

不知道如何解决这个问题,这让我发疯!不寻找直接答案,因为我不会学到任何东西,但也许会提供一些关于下一步该做什么的指导。提前谢谢大家了!

最佳答案

整数的最大值为2147483647。您输入的数字更大。扫描 long 而不是 int

或者,扫描字符串(因为您已经将整数转换为字符串)。

关于JAVA : "java.util.InputMismatchException" error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com