Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using Dr. Java Objective: Write a program where the user enters 10 words, and th

ID: 3793265 • Letter: U

Question

Using Dr. Java

Objective:

Write a program where the user enters 10 words, and they are sorted from the shortest length to the largest length. You may use any sorting method (like selection sort or bubble sort), but you may not use any of Java’s built in sorting methods.

Example Dialog:

Enter 10 strings and I'll sort them by their length. Smallest to largest.

big

bigger

biggest

small

smaller

smallest

huge

tiny

massive

average

The sorted strings are:

big

huge

tiny

small

bigger

biggest

smaller

massive

average

smallest

Explanation / Answer

StringSorting.java

import java.util.Scanner;


public class StringSorting {

  
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.println("Enter 10 strings and I'll sort them by their length. Smallest to largest.: ");
       String s[] = new String[10];
       for(int i=0; i<s.length; i++){
           s[i] = scan.next();
       }
       bubbleSort(s);
       System.out.println("The sorted strings are: ");
       for(int i=0; i<s.length; i++){
           System.out.println(s[i]);
       }
   }

public static void bubbleSort(String[] s) {

  
int n = s.length;
String temp ;

for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){

if(s[j-1].length() > s[j].length()){
//swap the elements!
temp = s[j-1];
s[j-1] = s[j];
s[j] = temp;
}

}
}

}

}

Output:

Enter 10 strings and I'll sort them by their length. Smallest to largest.:
big
bigger
biggest
small
smaller
smallest
huge
tiny
massive
average
The sorted strings are:
big
huge
tiny
small
bigger
biggest
smaller
massive
average
smallest

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote