2013-10-13 3 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++) 

다음과 같이 정렬 기능을 업데이트하십시오.

0

여기서 문제는 외부 및 내부 루프에서 동일한 진동을 증가시키고 있다는 것입니다. 외부 루프는 4 회 실행되지만 i이면 내부 루프가 값을 증가시킵니다. 내부 용 루프에서 다른 변수를 사용하십시오.

1

루프가 끝나면 문제가 있다고 생각합니다. i은 더 이상 scores.length보다 작지 않습니다. 이는 당신이 행 아래에 루프를 종료 할 때 기본적으로 바인딩의를 확인하는 것을 의미 :

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

당신이있어 J 대신 난을 증가하고 있습니다.

관련 문제