I want to read a couple of numbers from the console. The way I wanna do this is by having the user enter a sequence of numbers separated by a space. Code to do the following:
You want to set the delimiter like this:
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
while (sc.hasNextInt()){
int i = sc.nextInt();
//... do stuff with i ...
}
UPDATE:
The above code works well if the user inputs a number and then hits enter. When pressing enter without having entered a number the program the loop will terminate.
If you need (understood it more as a suggestion for usability) to enter the numbers space separated, have a look at the following code:
Scanner sc = new Scanner(System.in);
Pattern delimiters = Pattern.compile(System.getProperty("line.separator")+"|\\s");
sc.useDelimiter(delimiters);
while (sc.hasNextInt()){
int i = sc.nextInt();
//... do stuff with i ...
System.out.println("Scanned: "+i);
}
It uses a Pattern
for the delimiters. I set it to match a white space or a line separator. Thus the user may enter space separated numbers and then hit enter to get them scanned. This may be repeated with as many lines as necessary. When done the user just hits enter again without entering a number. Think this is pretty convenient, when entering many numbers.