Keep reading numbers until newline reached using a Scanner

前端 未结 2 2087
刺人心
刺人心 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 13:50

    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()).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题