获取最高整数时的Java-IndexOutOfBoundsException

获取最高整数时的Java-IndexOutOfBoundsException,java,loops,Java,Loops,我试图创建一个评分系统并获得最佳分数,但我的方法生成了IndexOutOfBoundsException,但我找不到超出arraylist界限的内容。有人能帮我吗 代码: 该方法是静态的,因为其他方法和变量也是静态的您错误地使用了i和p 在循环中,您将i设置为某个高分,该分数可能大于数组的大小,因此是IndexOutOfBoundsException public static Player getBestScore(Arena arena) { System.out.println(a

我试图创建一个评分系统并获得最佳分数,但我的方法生成了IndexOutOfBoundsException,但我找不到超出arraylist界限的内容。有人能帮我吗

代码:


该方法是静态的,因为其他方法和变量也是静态的

您错误地使用了
i
p

在循环中,您将
i
设置为某个高分,该分数可能大于数组的大小,因此是IndexOutOfBoundsException

public static Player getBestScore(Arena arena) {
    System.out.println(arena.getAPlayers().size());
    System.out.println(arena.getAPlayers().get(1).toString());
    int i = 0;
    Player player = null;

    // index of for loop is p
    for(int p = 0; p != arena.getAPlayers().size() - 1; i++) {

        System.out.println(arena.getAPlayers().get(p).toString());
        org.bukkit.entity.Player pla = arena.players.get(p);

        // If player's score is higher than current highscore(i)
        if(getArenaPlayer(pla).getScore() > i) {

            // Set current highscore(i) to this player's score
            i = getArenaPlayer(pla).getScore();
            player = getArenaPlayer(pla);
        }
    }
    return player;
}
这就是为什么你应该用更好的方式命名你的变量
如果使用
highscore
而不是
i
,或者可能使用
index
而不是
p
,则会大大减少混淆

几件事:

  • 您不需要在循环外声明
    i
  • 您不需要
    p
    变量
  • 你不应该使用
    =
    检查循环的
    (通常)
这:

不是一个好的for循环定义。要避免
索引自动边界异常
请以这种方式使用它

for(int i = 0; i < arena.getAPlayers().size(); i++) {
for(int i=0;i
使用:


与其他类似数组的结构一样,列表的索引从0开始。这一行
System.out.println(arena.getAPlayers().get(1.toString());
如果只有一个玩家,则可能会有问题。for循环条件应该是for(int i=0;ifor(int p = 0; p != arena.getAPlayers().size() - 1; i++) { // ^ ^ ^ different // ^ != WROOOONG!!!
for(int i = 0; i < arena.getAPlayers().size(); i++) {
for(int p = 0; p < arena.getAPlayers().size(); p++) {
for(int p = 0; p != arena.getAPlayers().size() - 1; i++) {