2013-10-13 5 views
1

Я изучаю объектно-ориентированные концепции прямо сейчас. Я написал простой класс, чтобы принимать оценки ввода пользователя, но я получаю исключение из-за пределов, и я не уверен, почему! Я не понимаю, почему это будет доступ к индексам более 4? Вот код:Получение ArrayIndexOutOfBoundsException и не знаю почему

рекордов класс, который я инстанцирование 5 объектов в массив:

public class HighScores 
{ 
    String name; 
    int score; 

    public HighScores() 
    { 
     this.name = ""; 
     this.score = 0; 
    } 
    public HighScores(String name, int score) 
    { 
     this.name = name; 
     this.score = score; 
    } 

    void setName(String name) 
    { 
     this.name = name; 
    } 

    String getName() 
    { 
     return this.name; 
    } 

    void setScore(int score) 
    { 
     this.score = score; 
    } 

    int getScore() 
    { 
     return this.score; 
    } 
} 

Программа манипулируют рекорды объекты:

import java.util.Scanner; 

public class HighScoresProgram 
{ 

    public static void main(String[] args) 
    { 
     HighScores[] highScoreObjArr = new HighScores[5]; 

     for (int i = 0; i < highScoreObjArr.length; i++) 
     { 
      highScoreObjArr[i] = new HighScores(); 
     } 
     initialize(highScoreObjArr); 
     sort(highScoreObjArr); 
     display(highScoreObjArr); 
    } 

    public static void initialize(HighScores[] scores) 
    { 
     Scanner keyboard = new Scanner(System.in); 
     for(int i = 0; i < scores.length; i++) 
     { 
      System.out.println("Enter the name for for score #" + (i+1) + ": "); 
      String temp = keyboard.next(); 
      scores[i].setName(temp); 
      System.out.println("Enter the the score for score #" + (i+1) + ": "); 
      scores[i].setScore(keyboard.nextInt()); 
     } 

    } 

    public static void sort(HighScores[] scores) 
    { 
     for(int i = 0; i < scores.length; i++) 
     { 
      int smallest = i; 

      for (int j = i; i < scores.length; i++) 
      { 
       if (scores[j].getScore() < scores[smallest].getScore()) 
        smallest = j; 
      } 

      HighScores temp = scores[i]; 
      HighScores swap = scores[smallest]; //This is where I'm getting the out of bounds exception. 
      scores[i] = swap; 
      scores[smallest] = temp; 

     } 
    } 

    public static void display(HighScores[] scores) 
    { 
     System.out.println("Top Scorers: "); 
     for(int i = 0; i < scores.length; i++) 
     { 
      System.out.println(scores[i].getName() + ": " + scores[i].getScore()); 
     } 

    } 

} 
+0

Вау, я чувствую себя идиотом! Я ударился головой, пытаясь понять это. Спасибо всем за помощь! – Whoppa

+0

Я рад, что вы смогли решить проблему. В будущем, если вы получаете исключение, опубликуйте все сообщение, чтобы облегчить его отладку, и в идеале обратите внимание на ту строку, из которой исключается исключение. – chrylis

ответ

5

я думаю, ниже линии проблема

for (int j = i; i < scores.length; i++) 

попробуйте обновить функцию сортировки, как показано ниже

public static void sort(HighScores[] scores) 
    { 
     for(int i = 0; i < scores.length; i++) 
     { 
      int smallest = i; 

      for (int j = i; j < scores.length; j++) 
      { 
       if (scores[j].getScore() < scores[smallest].getScore()) 
        smallest = j; 
      } 

      HighScores temp = scores[i]; 
      HighScores swap = scores[smallest]; //This is where I'm getting the out of bounds exception. 
      scores[i] = swap; 
      scores[smallest] = temp; 

     } 
    } 
0

Проблема заключается в том, что вы увеличиваете одинаковый vairable i во внешнем и внутреннем циклах. Ваш внешний цикл работает 4 раза, но внутренний цикл увеличивает значение, если i далее. Используйте другую переменную во внутреннем для цикла

1

Я думаю, что проблема в том, когда контур заканчивается, это означает, что i уже не меньше scores.length. Это означает, что вы в основном проверяя сшиваемых при выходе из цикла ниже линии:

for (int j = i; i < scores.length; i++) 
2
for (int j = i; i < scores.length; i++) 

Вы приращением я вместо J здесь.

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