Write a program that prompts the user to enter the number of students in a class
ID: 3694234 • Letter: W
Question
Write a program that prompts the user to enter the number of students in a class, the student names and their scores on a test. The program should print the student names (along with their scores) in decreasing order of their scores (use the selection sort as covered in class). Your sort should be implemented as a method (please see the following method header): public static void selectionSort( double[] score, String[] name) The scores should be an array of type double and the names an array of type String.
Hint 1: Once you read the number of students in a class, you can use that number to declare arrays of the appropriate size.
Hint 2: To read a name with a blank between the first and last name (e.g., Jim Bradford) from the console, we have to tell the Scanner to read a string until it hits the end of the line
Explanation / Answer
/** Sort_Students.java using selection sort to sort the scores of students **/
import java.util.Scanner;
public class Sort_Students {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int n = input.nextInt();
double[] score = new double[n];
String[] names = new String[n];
System.out.println("Enter student names and score:");
for (int i = 0; i < score.length; i++) {
names[i] = input.next();
input.nextLine(); //Use for next line of input
score[i] = input.nextDouble();
}
selectionSort(score, names);
System.out.println("Student names and scores in decreasing order:");
for (int i = names.length - 1; i >= 0; i--) {
System.out.println(names[i] + " : " + score[i]);
}
}
public static void selectionSort(double[] list, String[] names) {
for (int i = 0; i < list.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
// Swap names
String temp = names[currentMinIndex];
names[currentMinIndex] = names[i];
names[i] = temp;
}
}
}
}