Continue reading numbers until a new line is reached with a scanner

I want to read a couple of numbers from the console. The way I want to do this is to introduce the user into 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 can I stop when I reach a new line (while still maintaining easy to read code)? Addition a! HasNextLine () to the above argument causes it to exit the loop immediately. One solution would be to read the entire string and parse the numbers, but I think this breaks down the purpose of the hasNextInt () method.

+5
source share
2 answers

:

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator")); 
while (sc.hasNextInt()){
    int i = sc.nextInt();

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

UPDATE:

, , . enter, , .

(, ), , , :

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);
}

Pattern . . , , , Enter, . . , Enter, . , , .

+7

sc.nextLine() , String ( , ) . (. , , " ", , , Integer.parseInt()).

+2

All Articles