这里的新程序员,只是想完成我的编程作业(本学期的最后一个)!
基本上,赋值如下:编写一个读取整数的程序,找到最大的整数,并计算其出现次数。假设输入以0结尾。
我的代码: import 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)
不知道如何解决这个问题并让我疯狂!不寻找直接答案,因为我不会学到任何东西,但可能会对下一步该做什么有一些指导。提前谢谢大家!
答案 0 :(得分:2)
整数的最大值为2147483647
。输入中的数字更大。正在扫描long
而不是int
。
或者,扫描String
(因为您已经将Integer
转换为字符串)。
答案 1 :(得分:0)
36542454550
数字太大,无法容纳int
尝试使用double
或long
有符号整数的最大值为2147483647
答案 2 :(得分:0)
我建议你在这种情况下使用bigInteger,你可以在这里看到有关bigIntegers的更多信息:BigIntegers
答案 3 :(得分:0)
以下是执行您所描述的程序的示例:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
SortedMap<Long, Integer> maxMap = new TreeMap<>();
Long newLong = null;
do {
System.out.println("Please Enter a Integer: ");
newLong = scan.nextLong();
int count = maxMap.containsKey(newLong) ? maxMap.get(newLong) : 0;
maxMap.put(newLong, ++count);
} while (newLong.intValue() != 0);
System.out.println("Max number is: " + maxMap.lastKey());
System.out.println("Count: " + maxMap.get(maxMap.lastKey()));
scan.close();
}