gpt4 book ai didi

java - 对名单进行选择排序

转载 作者:行者123 更新时间:2023-11-30 08:14:39 26 4
gpt4 key购买 nike

所以我应该创建一个程序来询问类(class)规模。然后使用该人数,输入学生姓名和分数,直到填满类(class)人数。完成此操作后,我应该调用 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;
}
}
}

最佳答案

我已经评论了一个简单的解决方案,但实际上最好的办法是创建一类名册条目:

public class RosterEntry {
private String name;
private double score;

/*Accessors and Mutators*/
}

然后在你的main中您可以维护 RosterEntry 的列表或数组以便当您在选择排序中进行交换时,您交换 RosterEntry s 而不是单独的分数和名称。

关于java - 对名单进行选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com