javajava.util.scanner

how to sort input from java scanner?


I am working on a simple project in Java which need to take in a string through a Scanner object and then sort out the inputs which can be integers. These then need to be fed in pairs to run the program (which needs 2 input parameters).

An input could be: 2 4 % # -3 -5 q

which then needs to result in 2, 4, -3, -5 and q for quit. The rest needs to be sorted away and is not used.

How can I do this?


Solution

  • For the given input of 2 4 U s -4 6 a b c 10 100 3 -1 s q

    Scanner scanner = new Scanner(System.in);
    String input;
    while (!(input = scanner.next()).equalsIgnoreCase("q")) {
    
        if (input.matches("(\\+|-)?\\d+")) {
            System.out.print(input + " ");
        }
    
    }
    System.out.println();
    

    prints

    2 4 -4 6 10 100 3 -1