Using a scanner with a sequence of integers
I am writing a program to take a sequence of integers from the console for example.
1 5 3 4 5 5 5 4 3 2 5 5 5 3
then calculate the number of occurrences and print the following output:
0 - 0 eleven 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 entering the sequence, we must enter a non-integer character and press "Enter" to complete the scan and loop "for". Is there a way that we don't need to enter a non-integer character to complete the scan?
source to share
You can exit by pressing Enter and then Control-D.
If you don't want to do this, then there is no other way with Scanner
.
You will need to read the input in some other way, for example with BufferedReader
:
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
Scanner chopper = new Scanner(line);
Better yet (based on @ user3512478 approach ) with two scanners without BufferedReader
:
Scanner chopper = new Scanner(new Scanner(System.in).nextLine());
source to share
Best way IMO:
String str;
Scanner readIn = new Scanner(System.in);
str = readIn.nextLine();
String[] nums = str.split(" ");
int[] finalArray = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
finalArray[i] = Integer.parseInt(nums[i]);
return finalArray;
Hope this helps!
source to share
Best way: not only for this pattern, for any sequence input recognition, change the object separator Scanner
to get the recognized sequence.
Here in this case change the break separator to a space character (spaces). i "\\s"
. You can also use "\\s*"
to specify zero or more whitespace characters
This forces the scanner to check for spaces rather than waiting for the enter key to be pressed.
public static void main (String args[])
{
Scanner chopper = new Scanner(System.in).useDelimiter("\\s"); \\ Delimiter changed to whitespace.
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]);
}
}
source to share