I'm writing a program to take a sequence of integers from console, e.g.
1 5 3 4 5 5 5 4 3 2 5 5 5 3
then compute the number of occurrences and print the following output:
0 - 0 1 - 1 2 - 1 3 - 3 4 - 2 5 - 7 6 - 0 7 - 0 8 - 0 9 - 0
where the second number is the number of occurrences of the first number.
Code:
public static void main (String args[])
{
Scanner chopper = new Scanner(System.in);
System.out.println("Enter a list of number: ");
int[] numCount = new int[10];
int number;
while (chopper.hasNextInt()) {
number = chopper.nextInt();
numCount[number]++;
}
for (int i = 0; i < 10; i++) {
System.out.println(i + " - " + numCount[i]);
}
}
But after inputing the sequence, we must type a non-integer character and press "Enter" to terminate the Scanner and execute the "for" loop. Is there any way that we don't have to type a non-integer character to terminate the Scanner?