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

Java:检查ArrayList中一维数组索引0的值并更新索引1

问题分析与修复方案

你的代码核心问题集中在订单数据的重复添加逻辑、取消操作的异常处理以及数组引用复用这几个点上,以下是具体问题和修复步骤:

主要问题点

  1. 取消订单时的异常:当用户输入"A"取消当前商品时,代码仍会执行nbrConso = Integer.parseInt(UserInput),将字符串"A"转为整数会抛出NumberFormatException。
  2. 数组引用复用错误:Order数组只初始化一次,每次修改后添加到ArrayList,导致列表中所有元素都是同一个数组的引用,最终所有条目都会被覆盖为最后一次输入的数据。
  3. 商品ID存在性判断逻辑错误:ord.contains(Order[0] == idConso)是完全错误的写法——contains方法判断的是ArrayList中是否存在指定的int[]对象,而非数组内的商品ID值;且Order[0]已经被赋值为idConso,这个判断毫无意义。
  4. 未实现数量累加逻辑:即使找到已有商品ID,代码仍然直接添加新数组,没有对已有条目的数量进行累加,反而产生重复条目。

修复后的完整代码

package testes;

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

public class test_EX_24V1 {

    final static String NAMES[] = 
        {
                "Spa reine 25 ","Bru plate 50","Bru pét 50","Pepsi","Spa orange",
                "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche","Jus d'orange Looza", "Cécémel", 
                "Red Bull","Petit Expresso","Grand Expresso","Café décaféiné ","Lait Russe ","Thé et infusions",
                "Irish Coffee ","French Coffee ","Cappuccino","Cécémel chaud","Passione Italiano","Amour Intense",
                "Rhumba Caliente ","Irish Kisses ","Cuvée Trolls 25","Cuvee Trolls 50","Ambrasse-Temps 25","Ambrasse-Temps 50 ",
                "Brasse-Temps Cerises 25","Brasse-Temps Cerises 50","La Blanche Ste Waudru 25","Blanche Ste Waudru 50",
                "Brasse-Temps citr 25","Brasse-Temps citr 50","Spaghetti Bolo ","Tagl Carbonara","Penne poulet baslc ",
                "Tagl American","Tagl saum"
        };

    public static String getUserIntOrSpecificInputV2(String msg, String expectedAnsw, int min, int max) {
        int intInput = 0;
        String strAnsw = "";
        Scanner sc = new Scanner(System.in);
        do {
            System.out.println(msg);
            if (sc.hasNextInt()) {   // 判断是否输入整数
                intInput = sc.nextInt();
                if (intInput >= min && intInput <= max) {
                    return Integer.toString(intInput);
                } else {
                    System.out.println("La saisie doit être comprise entre " + min + " et " + max);
                }
            } else {  // 处理非整数输入
                strAnsw = sc.next();
                if (strAnsw.length() == 1 && expectedAnsw.toUpperCase().contains(strAnsw.toUpperCase())) {
                    return strAnsw.toUpperCase();
                } else {
                    System.out.println("Erreur de saisie : caractères autorisés " + expectedAnsw);
                }
            }
        } while (true);
    }//end getUserIntOrSpecificInputV2

    public static boolean checkTable(int[] table, int numberCheck) {
        int i = 0;
        while (i < table.length) {
            if (table[i] == numberCheck) {
                return true;
            }
            i++;
        }
        return false;
    }//fin check Table

    public static void getOrder(ArrayList<int[]> ord) {
        String UserInput;
        int idConso = 0, nbrConso = 0;

        UserInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable ou Q(Quitter) ", "Q", 1, NAMES.length);

        do {
            if (UserInput.equalsIgnoreCase("Q")) { // 退出程序
                System.out.println("Fin de Programme, Au Revoir");
                System.exit(-1);
            } else {
                idConso = Integer.parseInt(UserInput);
            }

            UserInput = getUserIntOrSpecificInputV2("Nombre de consommations pour " + NAMES[idConso - 1] + " ? /A(Annuler) /Q (Quitter)", "AQ", 1, 5000);

            if (UserInput.equalsIgnoreCase("Q")) {
                System.out.println("Fin de Programme, Au Revoir");
                System.exit(-1);
            } else if (UserInput.equalsIgnoreCase("A")) {
                // 取消当前商品,直接跳过后续处理
                UserInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable ou Q(Quitter) V (Valider le ticket) ", "QV", 1, NAMES.length);
                continue;
            }

            // 只有非取消非退出时才解析数量
            nbrConso = Integer.parseInt(UserInput);

            // 标记是否找到已有商品ID
            boolean found = false;
            // 遍历ArrayList查找对应ID
            for (int[] existingOrder : ord) {
                if (existingOrder[0] == idConso) {
                    // 找到后累加数量
                    existingOrder[1] += nbrConso;
                    found = true;
                    System.out.println("Quantité ajoutée au consommable existant");
                    break;
                }
            }

            // 未找到则添加新的订单数组
            if (!found) {
                int[] newOrder = new int[2];
                newOrder[0] = idConso;
                newOrder[1] = nbrConso;
                ord.add(newOrder);
                System.out.println("Nouveau consommable ajouté");
            }

            UserInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable ou Q(Quitter) V (Valider le ticket) ", "QV", 1, NAMES.length);

        } while (!UserInput.equalsIgnoreCase("V"));

        // 打印最终订单
        System.out.println("\nRésultat du ticket :");
        for (int[] item : ord) {
            System.out.println(NAMES[item[0] - 1] + " : " + item[1]);
        }
        System.out.println("Nombre de types de consommation : " + ord.size());
    }

    public static void main(String[] args) {
        ArrayList<int[]> order = new ArrayList<int[]>();
        getOrder(order);
    }
}

关键修复说明

  1. 取消操作的正确处理:当用户输入"A"时,直接执行continue跳过当前循环的后续逻辑,避免解析非整数的异常。
  2. 避免数组引用复用:每次添加新订单时,都创建新的int[] newOrder对象,确保ArrayList中的每个元素都是独立的数组。
  3. 正确的ID查找与数量累加:通过遍历ArrayList中的每个int[]元素,对比索引0的商品ID,找到后直接修改该数组的索引1值实现累加;未找到则添加新数组。
  4. 优化订单打印:将打印内容改为更友好的格式,显示商品名称和对应数量,而非单纯打印数组。

内容的提问来源于stack exchange,提问作者Just Relax قناة هدوء

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:10:32