You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java列表交替取数逻辑报错排查:玩家轮流取首元素反转列表问题

问题分析与修复

错误原因

你的代码会抛出IndexOutOfBoundsException,核心问题是:while循环只在开头判断列表不为空,但firstPlayer取完元素后,列表可能已经为空,此时代码仍会执行secondPlayer的取元素操作,直接触发索引越界。

举个实际执行流程的例子:
初始列表有5个元素,第三次循环时,firstPlayer取走最后1个元素,列表变为空,但代码还是会往下执行secondScore = list.get(i),空列表根本没有索引0的元素,自然报错。

另外代码里的变量i完全冗余,需求明确要求取首个索引,直接用0更清晰。

修复后的代码

修改循环逻辑,每次执行玩家操作前先判断列表状态,确保只有列表非空时才执行取元素操作:

import java.util.*;

public class GameScore {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        
        list.add(4);
        list.add(2);
        list.add(1);
        list.add(4);
        list.add(3);
        
        int firstPlayer = 0;
        int secondPlayer = 0;
        
        while (!list.isEmpty()) {
            // firstPlayer操作
            System.out.println("当前列表:" + list);
            int firstScore = list.get(0);
            list.remove(0);
            System.out.println("firstPlayer取走:" + firstScore);
            firstPlayer += firstScore;
            
            if (firstScore % 2 == 0) {
                Collections.reverse(list);
                System.out.println("反转后列表:" + list);
            }
            
            // 列表为空就直接跳出,不让secondPlayer再操作
            if (list.isEmpty()) {
                break;
            }
            
            // secondPlayer操作
            System.out.println("当前列表:" + list);
            int secondScore = list.get(0);
            list.remove(0);
            System.out.println("secondPlayer取走:" + secondScore);
            secondPlayer += secondScore;
            
            if (secondScore % 2 == 0) {
                Collections.reverse(list);
                System.out.println("反转后列表:" + list);
            }
        }
        
        System.out.println("分差:" + (firstPlayer - secondPlayer));
    }
}

关键调整点

  • 在firstPlayer操作后新增空列表判断,避免无效的secondPlayer操作
  • 移除冗余变量i,直接用索引0贴合需求
  • 优化打印信息,让执行过程更直观

内容的提问来源于stack exchange,提问作者patibanez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:13:08