string sort
Thu Jan 18 2024 18:23:53 GMT+0000 (Coordinated Universal Time)
Saved by
@login
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;
}
}
content_copyCOPY
Comments