user3681996 user3681996 -4 years ago 48
Java Question

Using Scanner with sequence of Integers

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?

Answer Source

You could get out by pressing Enter followed by Control-D.

If you don't want to do that, then there's no other way with a Scanner.

You will have to read the input by some other way, for example with a BufferedReader:

String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
Scanner chopper = new Scanner(line);

Even better (inspired by @user3512478's approach), with two Scanners, without BufferedReader:

Scanner chopper = new Scanner(new Scanner(System.in).nextLine());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download