0

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?

4
  • Do you really mean sort, or just eliminate everything but the integers? And why does it need to be fed in pairs? Commented Apr 1, 2024 at 15:45
  • u could use a regex to filter only numbers and the letter q, then split the input string by " ", and print pairs, if the value is q you can exit the program. Commented Apr 1, 2024 at 15:50
  • yea the pairs ill do later in the logic. Ok so regex sounds good. how would u write the syntax? Commented Apr 1, 2024 at 15:56
  • 1
    We call this filtering, not sorting. Filtering is when you remove members from a sequence that you don't want. Sorting is when you rearrange a sequence to put the members into a specific order. (Using the correct words for things will make it easier to communicate with other professionals. AND it will make it easier to search for answers.) Commented Apr 1, 2024 at 17:19

2 Answers 2

1
String input = "2 4 % # -3 -5  q";
String formatted = input.replaceAll("[^ 0-9q-]", "").replaceAll(" +", " ");

String[] split = formatted.split(" ");
// Loop through split

Our first goal is to remove everything that is uneccessary, to do that here's the regex I used in detail

  • ^ - Replace all the characters that are not equal to the characters provided in the regex.
    • - Keep all spaces
    • 0-9 - Keep all numbers
    • q - Keep all of the letter q
    • - - Keep all hyphens

Since we kept all spaces we will end up with the String 2 4 -3 -5 q. The spaces in between will cause an issue when we try to split it, so we replaces all multiple spaces (using the regex +) with a single space.

Now you can loop through split and pair them.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

thnx a lot! apprexciate it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.