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

如何将ArrayList元素与指定值映射后打印对应配对结果

问题原因

  • 原代码仅存储了companyId到ArrayList中,对应的profit是单次循环内的临时变量,每次循环都会被覆盖,程序运行完没有保留所有id对应的利润数据
  • 原代码存在索引越界隐患:如果输入重复的companyId,ArrayList不会新增元素,此时用循环变量i调用companiesId.get(i)会因为ArrayList实际长度小于i抛出索引越界异常

基于ArrayList的实现方案

你可以新增一个存储profit的ArrayList,保证两个列表相同索引位置的元素是互相对应的id和利润,修正后的代码如下:

import java.util.ArrayList;
import java.util.Scanner;

public class CompanyProfit {
    public static void main(String[] args) {
        ArrayList<Integer> companiesId = new ArrayList<>();
        ArrayList<Float> profits = new ArrayList<>(); // 新增存储利润的列表,和companiesId索引一一对应
        int numberOfCompanies = 10; // 示例值,可按需修改
        Scanner input = new Scanner(System.in);

        for(int i = 0; i < numberOfCompanies; i++) {
            int companyId = input.nextInt();
            // 仅处理未录入过的公司id
            if (!companiesId.contains(companyId)) {
                companiesId.add(companyId);
                float profit;
                // 直接用当前输入的companyId判断利润,避免索引越界
                if (companyId == 1) {
                    profit = 1000;
                } else if (companyId == 2) {
                    profit = 2000;
                } else {
                    profit = 0; // 其他id对应的利润可自行补充规则
                }
                profits.add(profit);
            }
        }
        input.close();

        // 遍历输出配对结果
        for (int j = 0; j < companiesId.size(); j++) {
            System.out.println(companiesId.get(j) + " " + profits.get(j).intValue());
        }
    }
}

补充:你也可以自定义一个包含companyId和profit属性的实体类,直接存储该实体类的对象到单个ArrayList中,代码可维护性更好,不需要额外维护两个列表的索引对应关系。

输出示例

输入10个包含1、2等数值的id后,输出会符合你要求的格式:

1 1000
2 2000
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:36:02