简体   繁体   中英

Java Index Out Of Bounds Exception ArrayList

I made a class with an ArrayList that holds "Student" Objects and I have a toString method that prints the Students test scores,name,etc. But I keep getting "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" here is my code, if you need to see any more code just comment

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

Driver Code:

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 message:

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)`
for (int test = 1; test <= 3; test++) 

应该这样吗

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

Probably you have an error not at this loop, but in Student class. First try this code

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

Then try change your inner loop to

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

Because most likely error is here


Added. Error is here

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

because

studentScores = new ArrayList <Integer> (NUMTESTS); 

NOT fill studentScores with 4 empty integer. After this line studentScores.size() return 0 insted of 4

There are some mistakes in your code.

Please update your code of getClassAverage() method from School2 class to

 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

And also toString() method of School2 class to

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

Also make changes in getAverage() method of Student2 class as below:

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

I hope you will get the point from where actually the exception is throwing, cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM