gpt4 book ai didi

java - 在单独的类中访问私有(private)变量?

转载 作者:行者123 更新时间:2023-11-29 07:48:54 25 4
gpt4 key购买 nike

这是家庭作业,所以我不指望你替我做。

我有一个程序可以按学生 ID 号对学生进行排序。问题是创建学生的学生类(class)(由我的老师提供,无法更改)的 ID 设置为私有(private),因此我无法在调用函数中访问它们。

这是学生类:

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() 因为它试图为方法赋值。

谢谢。

最佳答案

使用 Student 类提供的 getID 方法,这就是它的用途(也称为 getter)

students[lastPlace].getID();

您将遇到的下一个问题是没有 setter ......所以您不能(也不应该)分配 ID

相反,您应该交换实际的对象引用...

StudentQ temp = students[maxLoc];
students[maxLoc] = students[lastPlace];
students[lastPlace] = temp;

关于java - 在单独的类中访问私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902840/

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