为什么我无法访问其他课程的方法?

时间:2015-08-12 18:53:28

标签: java methods compiler-errors syntax-error text-files

我试图访问其他课程的方法,以便从学生的成绩册中获得平均分。我得到了#34;非法表达的开始"和"';'预期"错误。有人可以告诉我为什么吗?

     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是。事实上,我现在可能会失去积分。洛尔

1 个答案:

答案 0 :(得分:1)

Gradebook.java不是一个Object,而是一个文件,大概是一个包含一个名为Gradebook的类的文件。即使假设Gradebook类实现了可以在for循环中使用的东西,它仍然不是一个对象并且访问它静态将不起作用。

你可能至少需要一个new Gradebook()某个地方,也许还需要像getStudents()这样的方法。

显然,您希望访问Student对象集合。为此,必须在Gradebook类中包含这些对象的静态集合 - 然后您需要调用Gradebook.students或Gradebook.getStudents()之类的东西。或者必须在Gradebook类型的Object中包含这些对象的集合。在这种情况下,你需要这样一个对象,让我们在这里称它为aGradebook,并调用类似aGradebook.students()或aGradebook.getStudents()的东西 - 在这些情况下,成员或方法不会是静态的。