Keep reading numbers until newline reached using a Scanner

前端 未结 2 2078
刺人心
刺人心 2021-02-06 13:13

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:

2条回答
  •  不思量自难忘°
    2021-02-06 14:08

    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.

提交回复
热议问题