gpt4 book ai didi

java - 获取 ArrayIndexOutOfBoundsException 并且不确定为什么

转载 作者:行者123 更新时间:2023-11-29 10:15:24 26 4
gpt4 key购买 nike

我现在正在学习面向对象的概念。我写了一个简单的类来接受用户输入的分数,但我得到了一个越​​界异常,我不确定为什么!我不明白为什么这会访问超过 4 个的索引?这是代码:

我将 5 个对象实例化为一个数组的 HighScores 类:

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

程序操作 HighScore 对象:

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

}

}

最佳答案

我猜下面一行是问题

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;

}
}

关于java - 获取 ArrayIndexOutOfBoundsException 并且不确定为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com