import java.util.Arrays; import java.util.Scanner; public class StringSort { public static void main(String[] args) { Scanner ip = new Scanner(System.in); // Corrected: System.in should be passed as an argument System.out.println("Enter the number of words you are supposed to enter: "); int n = ip.nextInt(); ip.nextLine(); // Consume the newline character after reading the integer String[] str = new String[n]; for (int i = 0; i < str.length; i++) { System.out.println("Enter word " + (i + 1) + ":"); str[i] = ip.nextLine(); } System.out.println("Strings before they are sorted: " + Arrays.toString(str)); String[] str1 = sort(str); System.out.println("Strings after they are sorted are: " + Arrays.toString(str1)); } private static String[] sort(String[] str1) { String temp; for (int i = 0; i < str1.length - 1; i++) { for (int j = 0; j < str1.length - i - 1; j++) { if (str1[j].compareTo(str1[j + 1]) > 0) { temp = str1[j]; str1[j] = str1[j + 1]; str1[j + 1] = temp; } } } return str1; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter