簡體   English   中英

Java索引超出范圍異常ArrayList

[英]Java Index Out Of Bounds Exception ArrayList

我用一個包含“學生”對象的ArrayList制作了一個類,並且有一個toString方法可以打印出學生的考試成績,姓名等。 但是我不斷收到“ java.lang.IndexOutOfBoundsException:索引:0,大小: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)`
for (int test = 1; test <= 3; test++) 

應該這樣嗎

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

可能不是在此循環發生錯誤,而是在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

您的代碼中有一些錯誤。

請將您的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

我希望您能從異常拋出的地方得到點幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM