【发布时间】:2015-07-01 22:23:26
【问题描述】:
所以我应该创建一个询问班级人数的程序。然后使用该规模,输入学生姓名和分数,直到填满班级规模。之后,我应该调用一个 selectionSort 方法来按降序对分数进行排序。所以输出本质上是一个表格。一列是名称,另一列是分数,分数应该按降序排列,并带有适当的名称。我已经完成了大部分程序,我只是不知道如何将学生姓名与输入的分数联系起来。有人可以直接引导我吗?我不知所措。这是我的程序:
import java.util.Scanner;
public class Roster {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the size of the class: ");
int size = input.nextInt();
double[]score = new double[size];
String[]name = new String[size];
for(int i = 0; i < size; i++){
System.out.print("Please enter a student name: ");
String n = input.next();
name[i] = n;
System.out.print("Please enter " + n + "'s score: ");
double s = input.nextDouble();
score[i] = s;
System.out.println();
}
selectionSort(score,name);
System.out.print("THe class size is: " + size + "\n");
System.out.print("Name Score\n");
System.out.print("---- -----\n");
for(int i = 0; i < name.length; i++)
System.out.println(name[i] + " " + score[i] + " ");
System.out.println();
}
public static void selectionSort(double[] score, String[] name){
for(int i = score.length-1; i > 0; i--){
int maxIndex = 0;
for(int j = 1; j <= i; j++)
if(score[j] < score[maxIndex])
maxIndex = j;
double temp = score[i];
score[i] = score[maxIndex];
score[maxIndex] = temp;
}
}
}
【问题讨论】:
-
您可以做的一件事是,当您交换分数时,您可以交换具有相同索引的名称。
-
@mstbaum 我将如何交换具有相同索引的名称?
-
您有索引
i和索引maxIndex所以使用它们来索引您的name数组并执行与score数组相同的交换(您还需要一个临时字符串)。不过,我真的建议使用一个类,就像我在回答中描述的那样。
标签: java arrays sorting for-loop