Java Index Out of Bounds异常ArrayList

时间:2014-02-03 09:39:09

标签: java exception exception-handling

我创建了一个包含“Student”对象的ArrayList的类,并且我有一个toString方法,用于打印Students测试分数,名称等。但是我一直得到“java.lang.IndexOutOfBoundsException:Index:0,Size:0”这里是我的代码,如果你需要看到更多的代码只是评论

public class School2 {

    ArrayList <Student2> studentArray;// array of Student's


    /**
     * Constructor for School, creates an array of for ten Student's.
     */
    public School2() {
        final int NUMSTUDENTS = 10;
        studentArray = new ArrayList <Student2> (NUMSTUDENTS);
    }// end constructor

    /**
     * Method adds a student 'newStudent' to the array of Student's.
     * @param newStudent - Student to be added
     */
    public void add(Student2 newStudent) {
        studentArray.add(newStudent);
    }// end method

    /**
     * Method adds a Student whose name and test scores are passed in   parameter.
     * @param name - name of newly added Student
     * @param tests - array of test scores belonging to newly added Student
     */
    public void add(String name, ArrayList <Integer> testScores) {
        Student2 studentAdded = new Student2(name, testScores);
        studentArray.add(studentAdded);
    }// end method

    /**
     * Method adds a Student whose name is passed in parameter.
     * @param name - name of newly added Student
     */
    public void add(String name) {
        Student2 studentAdded = new Student2(name);
        studentArray.add(studentAdded);
    }// end method

    /**
     * Method adds a Student whose name is an empty String and test scores are 0.
     */
    public void add() {
        Student2 studentAdded = new Student2();
        studentArray.add(studentAdded);
    }// end method

    /**
     * Method removes all Student object 's' from array of Student's
     * @param s - Student to be removed from array of Student's
     */
    public void remove(Student2 s) {
        for (int i = 0; i < studentArray.size(); i++) {
            if (studentArray.get(i) == s) {
                studentArray.remove(i);
            }// end if statement
        }// end for loop
    }// end method

    /**
     * Method removes the Student whose index is passed in the parameter
     * @param index - index at which the Student is located
     */
    public void remove(int index) {
        studentArray.remove(index);
    }// end method


    /**
     * Method removes the Student whose name is passed in the parameter
     * @param name - name of Student to be removed
     */
    public void remove(String name) {
        for (int i = 0; i < studentArray.size(); i++) {
            if (studentArray.get(i).getName() == name) {
                studentArray.remove(i);
            }// end if statement
        }// end for loop
    }// end method

    /**
     * Method replaces the Student whose index is passed in the parameter with a
     * different Student object 'newStudent'
     * @param index - index of Student to be replaced
     * @param newStudent - Student object to replace other Student
     */
    public void replace(int index, Student2 newStudent) {
        studentArray.set(index, newStudent);
    }// end method

    /**
     * Method returns the student with the highest test score
     * @return - Student with the highest test score
     */
    public Student2 getHighScore() {
        int index = 0;
        int highScore = 0;
        for (int i = 0; i < studentArray.size(); i++) {

                if (studentArray.get(i).getHighScore() > highScore) {
                    index = i;
                    highScore = studentArray.get(i).getHighScore();
                }// end if statement


        }// end for loop
        return studentArray.get(index);
    }// end method

    /**
     * Method returns the class average
     * 
     * @return - class average of test scores
     */
    public int getClassAverage() {
        int totalScores = 0;
        int numTests = 0;
        for (int i = 0; i < studentArray.size(); i++) {

                for (int x = 1; x <= 3; x++) {
                    totalScores += studentArray.get(i).getScore(x);
                }
                numTests += 3;
        }// end for loop
        return (totalScores / numTests);
    }// end method

    /**
     * Getter method returns a Student whose index is passed in the parameter
     * @param index - index of Student object
     * @return - Student object
     */
    public Student2 getStudent(int index) {
        return (studentArray.get(index));
    }// end method

    /**
     * Getter method returns a Student whose name is passed in the parameter
     * @param name - name of Student
     * @return - Student object
     */
    public Student2 getStudent(String name) {
        int index = 0;
        for (int i = 0; i < studentArray.size(); i++) {
                if (studentArray.get(i).getName() == name) {
                    index = i;
                }// end if statement
        }// end for loop
        return (studentArray.get(index));
    }// end method

    /**
     * Method returns a string containing the names and test scores of all
     * students, the class average, and the highest score and the name of the
     * student with the highest score.
     */
    public String toString() {


        String school = "";
        for (int i = 0; i < studentArray.size(); i++) {
                school += "Name: " + studentArray.get(i).getName() + ":";
                //nested for loop gets all 3 tests and concatenates the scores to 'school' string
                for (int test = 1; test <= 3; test++) {
                    school += " test " + test + ": ";
                    school += studentArray.get(i).getScore(test);
                }// end nested for loop
                school += " Average: " + studentArray.get(i).getAverage();
                school += " High Score: " + studentArray.get(i).getHighScore()
                        + "\n";
            }// end nested for loop
        school += "Class Average: " + getClassAverage() + "\n";
        school += "Highest score\n";
        school += getHighScore() + "\n";

        return school;


    }// end method
}//end class


public class Student2 
{

    String studentName;// name of Student
    ArrayList <Integer> studentScores;// test scores of student
    final int NUMTESTS = 3;//Student has 3 different test scores

    /**
     * Constructor for Student2 class, sets name of student to an empty String
     * and test scores to 0.
     */
    public Student2(){
        studentName = "";
        studentScores = new ArrayList <Integer> (NUMTESTS);
    }//end constructor

    /**
     * Constructor for Student2 class, sets name to String passed in parameter
     * and test scores to 0.
     * @param name - name of student
     */
    public Student2(String name){
        studentName = name;
        studentScores = new ArrayList <Integer> (NUMTESTS);
    }//end constructor

    /**
     * Constructor for Student2 class, sets name and test scores to the String 
     * and array passed in the parameter
     */
    public Student2(String name, ArrayList<Integer> testScores){
        studentName = name;
        studentScores = testScores;
    }//end constructor

    /**
     * Constructor for Student2 class, sets the name and test scores to Student2 's'.
     * @param s - Student object
     */
    public Student2(Student2 s){
        studentName = s.getName();
        studentScores = new ArrayList <Integer> (NUMTESTS);
        for(int i = 0; i < studentScores.size(); i++){
            studentScores.add(s.getScore(i + 1));
        }//end for loop
    }//end constructor

    /**
     * Sets name of Student to String passed in parameter
     * @param name - name of Student
     */
    public void setName(String name) {
        studentName = name;
    }// end method

    /**
     * Getter method for Student's name
     * @return studentName - name of Student
     */
    public String getName() {
        return studentName;
    }// end method

    /**
     * Setter method which re-intializes a Student's test score at a given index
     * whose values are passed in the parameter
     * @param whichTest - test to be set
     * @param testScore - value of test to be set
     */
    public void setScore(int whichTest, int testScore) {
        if (whichTest >= 3) {
            studentScores.set(2, testScore);
        } else {
            studentScores.set((whichTest - 1), testScore);
        }
    }// end method

    /**
     * Setter method, re-intializes all test scores to the array passed in the
     * parameter
     * @param testScores - array of test scores
     */
    public void setScore(int[] testScores) {
        for(int i = 0; i < testScores.length; i++){
            studentScores.set(i, testScores[i]);
        }//end for loop
    }// end method

    /**
     * Getter method to get a Student's test score
     * @param whichTest - test number
     * @return score - score of the particular test number
     */
    public int getScore(int whichTest) {
        int score = 0;
        if (whichTest >= 3) {
            score = studentScores.get(2);
        } else {
            score = studentScores.get((whichTest - 1));
        }
        return score;
    }// end method

    /**
     * Method calculates the average of the Student's test scores
     * @return - average of Student's test scores
     */
    public int getAverage() {
        int total = 0;
        int numTests = 0;
        for (int i = 0; i < studentScores.size(); i++) {
            total += studentScores.get(i);
            numTests++;
        }
        return (total / numTests);
    }// end method

    /**
     * Method to get the Student's highest test score
     * @return highScore - Student's highest test score
     */
    public int getHighScore() {
        int highScore = 0;
        for (int i = 0; i < studentScores.size(); i++) {
            if (studentScores.get(i) > highScore) {
                highScore = studentScores.get(i);
            }//end if statement
        }//end for loop
        return highScore;
    }// end method

    /**
     * Method returns a String containing the Student's name, test scores,
     * average score and high score.
     */
    public String toString() {
        String student = "Name: " + getName() + ":";
        for(int test = 1; test <= studentScores.size(); test++){
            student += " test " + test + ": " + getScore(test);
        }
        student += " Average: " + getAverage();
        student += " High Score: " + getHighScore();

        return student;
    }// end method
}//end class

驱动程序代码:

School2 mySchool = new School2();
ArrayList<Student2> studentArr = mySchool.studentArray;

Student2 s = new Student2("Olive Oyl", randomScores());
mySchool.add(s);
mySchool.add("Popeye", randomScores());
mySchool.add("Bluto");
mySchool.add();

System.out.println(mySchool);

异常消息:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at Student2.getScore(Student2.java:107)
    at School2.toString(School2.java:176)
    at java.lang.String.valueOf(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at Driver.main(Driver.java:25)`

3 个答案:

答案 0 :(得分:0)

for (int test = 1; test <= 3; test++) 

这应该是

for (int test = 0; test < 3; test++)

答案 1 :(得分:0)

可能你在这个循环中没有错误,但是在Student类中。 首先尝试这段代码

String school = "";
for (int i = 0; i < studentArray.size(); i++) {
  school += "Name: " + studentArray.get(i).getName() + ":\n";
}
return school;

然后尝试将内循环更改为

for (int test = 1; test <= 3; test++) {
                school += " test " + test + ": ";
                school += studentArray.get(i-1).getScore(test);
            }// end nested for loop

因为最有可能的错误就在这里


加。 错误就在这里

public Student2(){
        studentName = "";
        studentScores = new ArrayList <Integer> (NUMTESTS);
}

,因为

studentScores = new ArrayList <Integer> (NUMTESTS); 

不要用4个空整数填充studentScores。 在此行之后,studentScores.size()返回0 insted of 4

答案 2 :(得分:0)

您的代码中存在一些错误。

请将您的getClassAverage()方法代码从School2类更新为

 public int getClassAverage() {
        int totalScores = 0;
        int numTests = 0;
        for (int i = 0; i < studentArray.size(); i++) {

                for (int x = 1; x <= studentArray.get(i).studentScores.size(); x++) {
                    totalScores += studentArray.get(i).getScore(x);
                }
                numTests += 3;
        }// end for loop
        return (totalScores / numTests);
    }// end method

还将School2类的toString()方法改为

public String toString() {
        String school = "";
        for (int i = 0; i < studentArray.size(); i++) {
                school += "Name: " + studentArray.get(i).getName() + ":";
                //nested for loop gets all 3 tests and concatenates the scores to 'school' string
                for (int test = 1; test <= studentArray.get(i).studentScores.size(); test++) {
                    school += " test " + test + ": ";
                    school += studentArray.get(i).getScore(test);
                }// end nested for loop
                school += " Average: " + studentArray.get(i).getAverage();
                school += " High Score: " + studentArray.get(i).getHighScore()
                        + "\n";
            }// end nested for loop
        school += "Class Average: " + getClassAverage() + "\n";
        school += "Highest score\n";
        school += getHighScore() + "\n";
        return school;
    }// end method

还要对Student2类的getAverage()方法进行更改,如下所示:

public int getAverage() {
    int total = 0;
    int numTests = 0;
    for (int i = 0; i < studentScores.size(); i++) {
        total += studentScores.get(i);
        numTests++;
    }
    if (numTests == 0) {
        return 0;
    } else {
        return (total / numTests);
    }
}// end method

我希望你能从异常投掷的地方得到重点,欢呼。