0

I'm trying to write a code that uses a scanner to input a list of words, all in one string, then alphabetizer each individual word. What I'm getting is just the first word alphabetized by letter, how can i fix this?

the code:

else if(answer.equals("new"))
    {
      System.out.println("Enter words, separated by commas and spaces.");
      String input= scanner.next();
      char[] words= input.toCharArray(); 
      Arrays.sort(words);
      String sorted= new String(words);
      System.out.println(sorted);

    }

Result: " ,ahy "

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70

2 Answers2

0

You're reading in a String via scanner.next() and then breaking that String up into characters. So, as you said, it's sorting the single-string by characters via input.toCharArray(). What you need to do is read in all of the words and add them to a String []. After all of the words have been added, use Arrays.sort(yourStringArray) to sort them. See comments for answers to your following questions.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
  • SO how would i set up the String[]? – user2399999 May 20 '13 at 02:00
  • String[] words= (input1, input 2, input 3..) or? – user2399999 May 20 '13 at 02:00
  • Yes, create a `String []` and add your strings to that string. Then sort based off of that array. You can add simply by doing something like `String [] ra= new String[10];` 10 was arbitrary. You can then add like so: `ra[0]="steve"; ra[1]="hello";`... If you keep track of your size, you can add to the next open slot in the array. – Steve P. May 20 '13 at 02:42
0

You'll need to split your string into words instead of characters. One option is using String.split. Afterwards, you can join those words back into a single string:

System.out.println("Enter words, separated by commas and spaces.");
String input = scanner.nextLine();

String[] words = input.split(",| ");
Arrays.sort(words);

StringBuilder sb = new StringBuilder();
sb.append(words[0]);
for (int i = 1; i < words.length; i++) {
    sb.append(" ");
    sb.append(words[i]);
}
String sorted = sb.toString();

System.out.println(sorted);

Note that by default, capital letters are sorted before lowercase. If that's a problem, see this question.

Community
  • 1
  • 1
Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
  • something about this isnt computing right, it's compiling but nothing prints out at the end – user2399999 May 20 '13 at 02:32
  • Works fine for me. Maybe there's a problem with your surrounding code? [Here](http://pastebin.com/3Dze5if9) is a stand-alone example for you to try, to demonstrate it does work. – Cairnarvon May 20 '13 at 03:01