Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep reading numbers until newline reached using a Scanner

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:

Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()){
    int i = sc.nextInt();

    //... do stuff with i ...
}

The problem is, how do I stop when reaching a new line (while keeping the easy-to-read code above)? Adding a !hasNextLine() to the argument above makes it quit the loop instantly. One solution would be reading the whole line and the parse out the numbers, but I think the kinda ruins the purpose of the hasNextInt() method.

like image 777
Snail Avatar asked Feb 21 '11 21:02

Snail


2 Answers

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.

like image 119
Chris Avatar answered Oct 05 '22 23:10

Chris


You could use sc.nextLine() to read an input line, and then construct a new Scanner from that String (there is a constructor overload that takes a String) and read the ints from the second Scanner. (Note: If this is what you meant by "reading the whole line and the parse out the numbers", I'll delete this answer, but it looked like you were talking about manually reading the numbers with Integer.parseInt()).

like image 37
Aasmund Eldhuset Avatar answered Oct 05 '22 22:10

Aasmund Eldhuset