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

二维数组元素比较逻辑及用户输入不完整问题咨询

解决二维数组输入不完整导致的异常问题

嘿,这个问题我之前做数组相关练习时也碰到过!核心问题出在两个地方:一是你的现有代码只校验了两个数组的总行数相等,没检查每一行的列数是否匹配;二是输入环节没有做校验,导致用户输入元素不足时,数组访问直接抛出ArrayIndexOutOfBoundsException。

下面给你分两种常见场景来解决:

场景1:提前声明数组的行列数(用户先输入行数、列数,再输元素)

这种情况我们可以在输入阶段就强制用户输入足够的元素,同时在比较时完善行列数的校验逻辑:

import java.util.Scanner;

public class ArrayCompare {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 输入第一个数组的行列数并构建数组
        int firstRows = getValidPositiveInt(scanner, "请输入第一个数组的行数:");
        int firstCols = getValidPositiveInt(scanner, "请输入第一个数组的列数:");
        int[][] firstArray = buildFixedSize2DArray(scanner, firstRows, firstCols, "第一个");
        
        // 输入第二个数组的行列数并构建数组
        int secondRows = getValidPositiveInt(scanner, "请输入第二个数组的行数:");
        int secondCols = getValidPositiveInt(scanner, "请输入第二个数组的列数:");
        int[][] secondArray = buildFixedSize2DArray(scanner, secondRows, secondCols, "第二个");
        
        // 执行数组比较
        compareTwo2DArrays(firstArray, secondArray);
    }
    
    // 获取有效的正整数输入(避免非数字或负数)
    private static int getValidPositiveInt(Scanner scanner, String prompt) {
        int input = 0;
        boolean isValid = false;
        do {
            System.out.print(prompt);
            if (scanner.hasNextInt()) {
                input = scanner.nextInt();
                if (input > 0) {
                    isValid = true;
                } else {
                    System.out.println("行数/列数必须是大于0的整数哦!");
                }
            } else {
                System.out.println("请输入有效的数字!");
                scanner.next(); // 清除无效输入,避免死循环
            }
        } while (!isValid);
        return input;
    }
    
    // 构建固定大小的二维数组,确保用户输入足够的元素
    private static int[][] buildFixedSize2DArray(Scanner scanner, int rows, int cols, String arrayName) {
        int[][] array = new int[rows][cols];
        System.out.printf("现在输入%s数组的元素,共%d行,每行%d个数字:\n", arrayName, rows, cols);
        
        for (int i = 0; i < rows; i++) {
            int elementCount = 0;
            while (elementCount < cols) {
                if (scanner.hasNextInt()) {
                    array[i][elementCount] = scanner.nextInt();
                    elementCount++;
                } else {
                    System.out.println("请输入有效的整数元素!");
                    scanner.next(); // 清除无效输入
                }
            }
            System.out.printf("第%d行输入完成 ✅\n", i + 1);
        }
        return array;
    }
    
    // 完善的二维数组比较逻辑
    private static void compareTwo2DArrays(int[][] first, int[][] second) {
        // 第一步:校验总行数是否相等
        if (first.length != second.length) {
            System.out.println("The size of the two arrays are not equals");
            return;
        }
        
        // 第二步:校验每一行的列数是否相等
        for (int i = 0; i < first.length; i++) {
            if (first[i].length != second[i].length) {
                System.out.println("The two arrays are not strictly identical arrays");
                return;
            }
        }
        
        // 第三步:逐个比较元素
        boolean isStrictlyIdentical = true;
        outerLoop: // 用标签直接跳出外层循环,提高效率
        for (int i = 0; i < first.length; i++) {
            for (int j = 0; j < first[i].length; j++) {
                if (first[i][j] != second[i][j]) {
                    isStrictlyIdentical = false;
                    break outerLoop;
                }
            }
        }
        
        // 输出结果
        System.out.println(isStrictlyIdentical ? 
            "The two arrays are strictly identical arrays" : 
            "The two arrays are not strictly identical arrays");
    }
}

场景2:用户直接输入元素(不提前声明行列,按行输入)

如果是用户不需要提前说行列数,直接输入每一行的元素(按回车结束一行,输入空行结束整个数组),那我们可以用动态列表来接收元素,避免元素不足的问题:

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

public class DynamicArrayCompare {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 动态构建第一个数组
        List<List<Integer>> firstList = buildDynamic2DList(scanner, "第一个");
        // 动态构建第二个数组
        List<List<Integer>> secondList = buildDynamic2DList(scanner, "第二个");
        
        // 转成二维数组(也可以直接用列表比较)
        int[][] firstArray = convertListTo2DArray(firstList);
        int[][] secondArray = convertListTo2DArray(secondList);
        
        // 执行比较
        compareTwo2DArrays(firstArray, secondArray);
    }
    
    // 动态构建二维列表,用户输入一行元素用空格分隔,空行结束输入
    private static List<List<Integer>> buildDynamic2DList(Scanner scanner, String arrayName) {
        List<List<Integer>> arrayList = new ArrayList<>();
        System.out.printf("请输入%s数组的元素:每行输入用空格分隔数字,输入空行结束输入\n", arrayName);
        
        scanner.nextLine(); // 清除之前的换行符,避免直接进入空行判断
        String line;
        while (!(line = scanner.nextLine()).isEmpty()) {
            String[] elementStrs = line.trim().split("\\s+");
            List<Integer> row = new ArrayList<>();
            for (String str : elementStrs) {
                try {
                    row.add(Integer.parseInt(str));
                } catch (NumberFormatException e) {
                    System.out.println("跳过无效元素:" + str);
                }
            }
            if (!row.isEmpty()) {
                arrayList.add(row);
            }
        }
        return arrayList;
    }
    
    // 将二维列表转成二维数组
    private static int[][] convertListTo2DArray(List<List<Integer>> list) {
        int[][] array = new int[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            List<Integer> row = list.get(i);
            array[i] = new int[row.size()];
            for (int j = 0; j < row.size(); j++) {
                array[i][j] = row.get(j);
            }
        }
        return array;
    }
    
    // 复用之前完善的比较方法
    private static void compareTwo2DArrays(int[][] first, int[][] second) {
        if (first.length != second.length) {
            System.out.println("The size of the two arrays are not equals");
            return;
        }
        
        for (int i = 0; i < first.length; i++) {
            if (first[i].length != second[i].length) {
                System.out.println("The two arrays are not strictly identical arrays");
                return;
            }
        }
        
        boolean isIdentical = true;
        outerLoop:
        for (int i = 0; i < first.length; i++) {
            for (int j = 0; j < first[i].length; j++) {
                if (first[i][j] != second[i][j]) {
                    isIdentical = false;
                    break outerLoop;
                }
            }
        }
        
        System.out.println(isIdentical ? 
            "The two arrays are strictly identical arrays" : 
            "The two arrays are not strictly identical arrays");
    }
}

核心改进说明

  1. 输入阶段的防御性编程:无论是固定行列还是动态输入,都确保用户提供的元素数量符合预期,从根源上避免数组越界异常。
  2. 完善的比较逻辑:不仅检查总行数,还检查每一行的列数,确保两个数组的结构完全一致后再比较元素。
  3. 代码可读性与效率:使用标签跳出外层循环,避免不必要的元素比较;添加输入提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:18:12