2014-02-03 3 views
0

Я создал класс с ArrayList, который содержит объекты «Студент», и у меня есть метод toString, который печатает результаты тестов, имя и т. Д. Но я получаю "java.lang.IndexOutOfBoundsException: Индекс: 0 Размер: 0" Вот мой код, если вы хотите увидеть больше кода просто комментарийJava Index Out Of Bounds Exception ArrayList

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 Код:

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)` 
+0

Что должен делать внутренний контур? –

+4

'for (int test = 1; test <= 3; test ++)' должно ли это быть 'for (int test = 0; test <3; test ++)' – thumbmunkeys

+2

Ваш 'ArrayList' пуст. – christopher

ответ

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

Если это будет

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

thn wat будет ??? – Kick

+1

Lol кто-то прокомментировал этот точный ответ некоторое время назад. Кроме того, это не имело бы никакого отношения к IndexOutOfBoundsException –

+0

Индекс массива всегда начинался с 0 –

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); 

НЕ заполняйте studentScores с 4 пустыми целым числом. После этой строки studentScores.size() return 0 insted of 4

+1

И почему это должно работать? Это не так. Вы даже не знаете, в чем проблема. –

+0

Отредактированный пост. –

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 

А также ToString() метод класса School2 к

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 

также вносить изменения в getAverage() метод Класс Student2, как указано ниже:

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 

Надеюсь, вы узнаете, откуда исключение бросает, приветствует.

Смежные вопросы