从数组中返回类类型

时间:2015-12-16 02:57:55

标签: java

我在这里得到了一个叫做Classrooms的课,我的getTopStudent方法,它说我的变量“topStudent”还没有初始化,我错过了什么?,并不是所有内容都在我AP的视频中解释java课程

public class Classroom
{
    Student[] students;
    int numStudentsAdded;

    public Classroom(int numStudents)
    {
        students = new Student[numStudents];
        numStudentsAdded = 0;
    }

    public Student getTopStudent()
    {
        Student topStudent;
        for(int i = 1; i < students.length; i++)
        {

            if(students[i].getAverageScore() > students[i - 1].getAverageScore())
            {
                topStudent = students[i];
            }
            else
            {
                topStudent = students[i - 1];
            }

        }
        return topStudent;
    }

    public void addStudent(Student s)
    {
        students[numStudentsAdded] = s;
        numStudentsAdded++;
    }

    public void printStudents()
    {
        for(int i = 0; i < numStudentsAdded; i++)
        {
            System.out.println(students[i]);
        }
    }
}

我的学生班都在工作,没有任何错误,不要以为要解决这个问题。

测试器:

public class ClassroomTester extends ConsoleProgram
{
    public void run()
    {
        Classroom c = new Classroom(2);

        Student ada = new Student("Ada", "Lovelace", 12);
        ada.addExamScore(44);
        ada.addExamScore(65);
        ada.addExamScore(77);

        Student alan = new Student("Alan", "Turing", 11);
        alan.addExamScore(38);
        alan.addExamScore(24);
        alan.addExamScore(31);

        // add students to classroom
        c.addStudent(ada);
        c.addStudent(alan);
        c.printStudents();

        Student topStudent = c.getTopStudent();
        System.out.println(topStudent);
    }
}

2 个答案:

答案 0 :(得分:0)

它应该抱怨,因为如果getTopStudent()中的for循环永远不会运行,topStudent将保持未初始化状态。使用Student topStudent = null

答案 1 :(得分:0)

您可以假设学生人数大于1,但是编译器检测到学生对象在学生为0的情况下未被初始化的可能性。因此您编写的代码应该确保所有流程都是涵盖

你应该有这样的代码

public class Classroom
{
    Student[] students;
    int numStudentsAdded;

    public Classroom(int numStudents)
    {
        students = new Student[numStudents];
        numStudentsAdded = 0;
    }

    public Student getTopStudent()
    {
       if(students == null|| students.lenght ==0){
               return null;
        }          
        Student topStudent;
        for(int i = 1; i < students.length; i++)
        {

            if(students[i].getAverageScore() > students[i - 1].getAverageScore())
            {
                topStudent = students[i];
            }
            else
            {
                topStudent = students[i - 1];
            }

        }
        return topStudent;
}