关闭。这个问题是 not reproducible or was caused by typos 。它目前不接受答案。
想改进这个问题?更新问题,使其成为 Stack Overflow 的 on-topic。
6年前关闭。
Improve this question
我正在尝试访问其他类(class)的方法,以便从学生的成绩册中获取平均值。我得到“非法的表达开始”和“';'预期的”错误。有人能告诉我为什么吗?
public double getClassAverage{
double a = 0.0;
for(Student s : Gradebook.java){
a+=s.numericScore();
}
return a / 17;
}
这是示例成绩簿:
Ozzy:Osbourne:666666666:64:100:90:80:70:60:50:40:30:75:50:40:20:50
Paris:Hilton:234456789:32:100:100:60:50:75:40:90:100:75:80:90:85:90
Honey:Booboo:112117654:7:20:15:0:0:40:0:50:30:50:25:40:20:20
Bilbo:Baggins:481516234:50:100:100:80:80:60:90:100:100:80:75:90:85:80
Bill:Gates:642767638:57:100:100:100:100:100:100:100:100:100:100:100:100:100
那不是成绩册课,这是成绩册课:
公开课成绩册
{
// maximum number of students per class
private static final int MAX_NUMBER_OF_STUDENTS = 30;
// array of students in the gradebook
private Student [] students;
// index (into students array)
// where we should insert next student
private int currentStudentIndex;
// constructor with Student array
public Gradebook(Student [] students)
{
int i;
this.students = new Student[MAX_NUMBER_OF_STUDENTS];
for (i = 0; i < students.length && i < MAX_NUMBER_OF_STUDENTS; i++)
{
this.students[i] = students[i];
}
this.currentStudentIndex = i;
}
// no-arg constructor
public Gradebook()
{
// allocate enough space for the max number of students
this.students = new Student[MAX_NUMBER_OF_STUDENTS];
this.currentStudentIndex = 0;
}
public void addStudent(Student s)
{
if (currentStudentIndex >= MAX_NUMBER_OF_STUDENTS)
{
// too many students: do not add...print an error and return
System.out.println("Could not add " + s.getName() + "...class is full");
return;
}
this.students[currentStudentIndex] = s;
currentStudentIndex++;
}
public int getNumberOfStudentsInGradebook()
{
return currentStudentIndex;
}
public Student getStudent(int index)
{
return students[index];
}
}
我想从样本成绩簿中取出每个学生并获得他们的平均成绩。我有一个单独的文件,我不想发布,因为我认为 getClassAverage 所在的代码太多。事实上,我可能会因为我现在所拥有的而丢分。哈哈
最佳答案
Gradebook.java 不是一个对象,而是一个文件,大概包含一个名为 Gradebook 的类。即使假设 Gradebook 类实现了可以在 for 循环中使用的东西,它仍然不是一个对象,并且静态访问它是行不通的。
您可能至少需要一个 new Gradebook()
某处,可能也是像 getStudents()
这样的方法.
显然,您想访问学生对象的集合。为此,Gradebook 类中必须有这些对象的静态集合 - 然后您需要调用 Gradebook.students 或 Gradebook.getStudents() 之类的东西。或者必须在成绩簿类型的对象中包含这些对象的集合。在这种情况下,您将需要这样一个对象,我们在这里将其称为 aGradebook,并调用类似 aGradebook.students() 或 aGradebook.getStudents() 的东西 - 在这些情况下,成员或方法不会是静态的。
关于java - 为什么我不能访问这个其他类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31973237/