I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
i know it's old discuss :) i tested below code it's worked
Scanner has a method called hasNext():
You want to take the numbers in as a String and then use
String.split(" ")
to get the 3 numbers.Each index of the array will hold a String representation of the numbers which can be made to be
int
s byInteger.parseInt()
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Try this
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use
Scanner.nextInt()
the number of times you would like to get an integer.