IndexOutOfBoundsException

IndexOutOfBoundsException

我正在尝试创建一个评分系统并获得最佳评分,但是我的方法生成了IndexOutOfBoundsException,但我找不到arraylist范围之外的内容,有人可以帮助我吗?

码:

 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;
    for(int p = 0; p != arena.getAPlayers().size() - 1; i++) {
        System.out.println(arena.getAPlayers().get(i).toString());
        org.bukkit.entity.Player pla = arena.players.get(i);
        if(getArenaPlayer(pla).getScore() > i) {
            i = getArenaPlayer(pla).getScore();
            player = getArenaPlayer(pla);
        }
    }
    return player;
}


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

最佳答案

您错误地使用了ip
在循环中,将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可以减少混乱!

关于java - Java-获取最大整数的IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30529682/

10-10 08:51