这是家庭作业,所以我不希望您为我做。
我有一个程序,可以按学生的学生证号对学生进行排序。问题在于,创建学生的学生班级(由我的老师提供,不能更改)将ID设置为私有,因此我无法在调用函数中访问他们。
这是学生班:
public class StudentQ {
private String name;
private int id;
private double avg;
StudentQ(String sname, int sid, double average){
name=sname;
id=sid;
avg=average;
}
// Note this uses the String static method format to produce a string
// in the same way that System.out.printf does
public String toString(){
return String.format("%15s [%6d]:%7.2f", name,id,avg);
}
public String getName(){
return name;
}
public int getID(){
return id;
}
public double getAverage(){
return avg;
}
public void setAverage(double newavg){
avg=newavg;
}
}
这是我的分类课:
static void sortByID(StudentQ[] students) {
for (int lastPlace = students.length-1; lastPlace > 0; lastPlace--) {
int maxLoc = 0;
for (int j = 1; j <= lastPlace; j++) {
if (students[j].getID() > students[maxLoc].getID()) {
maxLoc = j;
}
}
int temp = students[maxLoc].getID();
*students[maxLoc].id = students[lastPlace].id;
students[lastPlace].id= temp;*
}
}
现在的样子,这给了我一个错误,并显示错误消息:StudentQ.id字段不可见,并且我无法使用.getID(),因为它试图将值分配给方法。
谢谢。
最佳答案
使用getID
类提供的Student
方法,这就是它的用途(又称吸气剂)
students[lastPlace].getID();
您将遇到的下一个问题是没有设置程序的事实……因此您不能(也不应该)分配ID的
相反,您应该交换实际的对象引用...
StudentQ temp = students[maxLoc];
students[maxLoc] = students[lastPlace];
students[lastPlace] = temp;