【发布时间】:2015-04-27 02:26:42
【问题描述】:
我必须制作一个程序,让用户输入任意数量的学生,询问每个学生的姓名和年级。因此,如果我说 2 个学生,我会输入 billy smith,然后是 54,然后它会问我第二个学生的名字,john smith,然后是年级,81。然后它会按成绩的降序输出姓名和成绩。它会输出:
name---------grades
------------------
John smith 81
billy smith 54
除了打印出来,我什么都有。我需要它来打印带有等级的名称。这是我所拥有的:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
Double[] array = new Double[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] =input.next();
System.out.print("Enter the student's score: ");
array[i] = (Double) input.nextDouble();
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
selectionSort(names, array);
System.out.println(Arrays.toString(names));
}
public static void selectionSort(String[] names, Double[] array) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
Double currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
}
}
【问题讨论】:
-
创建一个 Class 来存储姓名/成绩对,然后使用自定义的
Comparator对列表进行排序,这将根据成绩值进行排序。
标签: java