지금 당장은 객체 지향 개념에 대해 배우고 있습니다. 나는 사용자 입력 점수를 받아들이 기 위해 간단한 클래스를 썼지 만 범위를 벗어난 예외가 발생하고 왜 그런지 잘 모르겠습니다! 이것이 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());
}
}
}
와우 나는 바보처럼 느껴진다! 나는 그것을 고치려고 머리를 세게 치고 있었다. 도움을 주신 모든 분들께 감사드립니다! – Whoppa
문제가 해결되어 기쁩니다. 앞으로 예외가 발생하면 전체 메시지를 게시하여 디버그를 쉽게하고 예외가 발생하는 행을 이상적으로 메모하십시오. – chrylis