0

I'm having trouble with my program. I need to enter only capital letters, R,B,W. Validate the correct input and then sort the string. Output should be sorted with R's first, B's second and W's third. I can only get the alphabetized output, not the needed output. I don't know what to do next.

System.out.print("Enter a string of capital letters made up of R, B, W:  ");
Scanner s = new Scanner(System.in);
String letters;

for (letters = s.nextLine(); !letters.matches("[RBW]+"); letters = s.nextLine())
{
    System.out.println("Invalid entry. Please enter the correct letters.");
}

System.out.println("Thank you");
char[] sort2 = letters.toCharArray();
Arrays.sort(sort2);
String sorted = new String(sort2);

System.out.println("Here are your letters sorted:" +sorted);
0

2 Answers 2

1

You could do something like this. Have three different StringBuilders and add each letter to them accordingly. Then concatenate them in the right order when its done looping through the letters.

StringBuilder r = new StringBuilder();
StringBuilder w = new StringBuilder();
StringBuilder b = new StringBuilder();

for (char c : letters.toCharArray()){
    switch(c){
        case 'R' : r.append(c); break;
        case 'B' : b.append(c); break;
        case 'W' : w.append(c); break;
    }
}

String sorted = r.toString() + b.toString() + w.toString();
System.out.println("Here are your letters sorted:" + sorted);
Sign up to request clarification or add additional context in comments.

3 Comments

@Chris I was thinking of a more complex solution too, but then I was thinking, there's gotta be an easier way ;)
WOW! Great solution! I have been struggling on this for a while now. This makes logical sense.
Thank you!This was a great help!
0

Arrays.sort(char[]) uses natural ordering, so you'll get Bs then Rs then Ws.

If you want an other sort order you have to implement your own Comparator and use Arrays.sort(T[], Comparator). Therefore you have to convert it to an Object array.

Arrays.sort(sort2, new Comparator<Char>() {
    public int compare(Char o1, Char o2) {
        if (Char.valueOf("R").equals(o1)) {
            if (Char.valueOf("R").equals(o2)) {
                return 0;
            } else {
                return -1;
            }
        } else if (Char.valueOf("B").equals(o1)) {
        ....

    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.