user2399999
user2399999

Reputation: 1

alphabetizing a list from a single string

I'm trying to create a program that takes in a single string and sorts the words by alphabetical order, this is what i have at the moment but nothing is printing out:

System.out.println("Enter words, sepaated by commas and spaces");
      String input= scanner.next();
      String[] words= input.split(" ");
      Arrays.sort(words);
      StringBuilder zoop= new StringBuilder();
      for(int i=1; i<words.length; i++){
       zoop.append(" ");
       zoop.append(words[i]);
      }
      String sorted= zoop.toString();
      System.out.println(sorted);

Upvotes: 0

Views: 124

Answers (3)

Vaishak Suresh
Vaishak Suresh

Reputation: 5855

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

and

for(int i=0; i<words.length; i++){

scanner.next() only returns the next complete token. In your case, it returns just the first word. Since the for loop started with 1 instead of 0, the program printed nothing.

Upvotes: 2

Ryan Stewart
Ryan Stewart

Reputation: 128929

You have two errors that cooperate to produce no output. First, look at the difference between Scanner.next() and Scanner.nextLine(). Then realize that arrays are 0-based in Java and take a second look at your for loop.

Upvotes: 1

xuanji
xuanji

Reputation: 5097

for(int i=1; i<words.length; i++){

should be

for(int i=0; i<words.length; i++){

Upvotes: 0

Related Questions