Reputation: 1
new programmer here, just trying to finish my programming assignment (last one of the semester)!
Basically, assignment is as follows: Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume the input ends with 0.
My code: 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);
}
}
}
Code will work fine for input such as: 3525550 (max number is 5, occurrences is 4)
Code will not work for input such as: 36542454550 For this iput, I receive the following error: Exception in thread "main" java.util.InputMismatchException: For input string: "36542454550" at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at IntCount.main(IntCount.java:13)
No idea how to fix this and its driving me nuts!! not looking for direct answer, as I wouldn't learn anything, but maybe some guidance on what to do next. Thank you all ahead of time!
Upvotes: 0
Views: 160
Reputation: 679
Here's an example of a program that does what you described:
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();
}
Upvotes: 0
Reputation: 112
I recommend you to use bigInteger in this kind of situations, you can see more information about bigIntegers here: BigIntegers
Upvotes: 0
Reputation: 2101
Integers have a max value of 2147483647
. The number in your input bigger. Scan for a long
instead of int
.
Alternatively, scan for a String
(since you're already converting your Integer
to a string).
Upvotes: 2
Reputation: 1349
36542454550
is too big of a number to hold in an int
Try using double
or long
The max value for a signed integer is 2147483647
Upvotes: 0