Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

outputting a sentence from shortest word to longest

This is what I currently have been trying to get an output like this:

input:  this is a sentence
output: a is this sentence
import java.util.Scanner;
Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentance:");
        String text = input.nextLine();
        String[] words = text.split("");
        String temp;

        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < (words.length - 1); j++) {
                if (words[j].compareTo(words[j + 1]) < 0) {
                    temp = words[j];
                    words[j] = words[j + 1];
                    words[j + 1] = temp;

                }
            }
            System.out.print(words[i]);
        }
    }
}

If anyone could help that would be great!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may convert the input to a list and then sort using a lambda:

Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence:");
String text = input.nextLine();
List<String> words = Arrays.asList(text.split(" "));
words.sort(Comparator.comparingInt(String::length));
System.out.println(String.join(" ", words));

This prints (for input this is a sentence):

 a is this sentence
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading