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

Java中如何根据用户输入删除数组中的指定元素

Java数组删除指定索引元素实现方案

Java的数组是定长结构,本身不支持直接删除元素,需要通过创建长度减1的新数组,拷贝除目标索引外的所有元素的方式实现删除效果。

你可以在标注的// and remove the element that the user entered. <--- this is the one . i dont know where to start.位置插入以下代码:

// 先校验输入的索引合法性
if (removeIndex < 0 || removeIndex >= teamNo) {
    System.out.println("输入的队伍编号无效,删除操作取消");
} else {
    // 初始化长度减1的新数组
    String[] newTeamName = new String[teamNo - 1];
    int[] newTeamScore = new int[teamNo - 1];
    // 遍历原数组,跳过要删除的索引,拷贝其余元素到新数组
    for (int i = 0, j = 0; i < teamNo; i++) {
        if (i != removeIndex) {
            newTeamName[j] = teamName[i];
            newTeamScore[j] = teamScore[i];
            j++;
        }
    }
    // 替换原数组、更新队伍总数
    teamName = newTeamName;
    teamScore = newTeamScore;
    teamNo--;
    System.out.println("删除成功,当前剩余队伍数:" + teamNo);
}

// 补充说明:你当前的删除逻辑写在所有赛事的循环中,如果只需要第一场赛事结束后删除队伍,可把删除相关代码包裹在if(a == 0)判断里,避免每场赛事结束都触发删除操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:18:02