import java.util.Scanner;
public class StudentNamesSorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the number of students
System.out.print(“Enter the number of students: “);
int numberOfStudents = scanner.nextInt();
scanner.nextLine(); // Consume the newline
// Array to store student names
String[][] studentNames = new String[numberOfStudents][];
// Get student names from the user
System.out.println(“Enter the names of the students:”);
for (int i = 0; i < numberOfStudents; i++) {
studentNames[i] = new String[] {
scanner.nextLine()
};
}
// Sort the student names by length without using Arrays.sort
sortNamesByLength(studentNames);
// Print the sorted names
System.out.println(“Sorted names of students by length:”);
for (String[] name: studentNames) {
System.out.println(name[0]);
}
}
public static void sortNamesByLength(String[][] names) {
for (int i = 0; i < names.length – 1; i++) {
for (int j = 0; j < names.length – i – 1; j++) {
if (names[j][0].length() > names[j + 1][0].length()) {
// Swap names[j] and names[j + 1]
String[] temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
}
}
Leave a Reply