Java二维数组列最大值提取程序遇数组越界问题求助
解决二维数组列最大值提取的数组越界问题
Hey there! Let's work through fixing your ArrayIndexOutOfBoundsException and getting your program to correctly extract the maximum value from each column of your 2D array.
原代码的核心问题
Let's break down why you're hitting that error and where the logic is off:
- 二维数组维度搞反了: You declared
int[][] table = new int [col][row];but then tried to accesstable[j][i]wherejruns up torow-1. Ifrowis larger thancol, this will immediately cause an out-of-bounds error—since your array only hascolrows, you can't access rows beyond that. - 最大值存储数组定义错误: Your
tarray is sized forrowelements, but you need to store one maximum per column (so it should be sized forcolelements instead). - 最大值赋值逻辑混乱: You're incrementing
mand assigning tot[m]every time you find a larger value, which would filltwith multiple values per column instead of just the final maximum for each column.
修正后的代码
import java.util.Arrays; import java.util.Scanner; public class ColumnMaxExtractor { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 先输入行数和列数,明确顺序避免维度混淆 System.out.println("请输入行数:"); int row = sc.nextInt(); System.out.println("请输入列数:"); int col = sc.nextInt(); // 正确定义二维数组:行数为row,每行包含col个元素 int[][] table = new int[row][col]; // 结果数组长度等于列数,用来存每列的最大值 int[] columnMaxes = new int[col]; // 填充二维数组 System.out.println("请输入数组元素(按行依次输入):"); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { table[i][j] = sc.nextInt(); } } // 遍历每一列,查找最大值 for (int i = 0; i < col; i++) { // 初始化当前列的最大值为该列第一行的元素 int max = table[0][i]; // 遍历当前列的所有行,更新最大值 for (int j = 1; j < row; j++) { if (table[j][i] > max) { max = table[j][i]; } } // 将当前列的最大值存入结果数组 columnMaxes[i] = max; } // 输出最终结果 System.out.println("每列的最大值为:"); System.out.println(Arrays.toString(columnMaxes)); sc.close(); } }
关键修正点说明
- 数组维度对齐: We now define
tableasnew int[row][col], matching the input order of rows first, then columns. This ensures we never try to access a row or column that doesn't exist in the array. - 结果数组大小匹配:
columnMaxesis sized tocolelements, which exactly matches the number of columns we need to process. - 清晰的最大值查找逻辑: For each column, we start with the first element as the initial max, then iterate through all remaining rows in that column to update the max if a larger value is found. Finally, we store that single, final maximum in the results array.
示例运行效果
If you input:
3 2 1 5 3 2 4 7
The output will be:
每列的最大值为: [4, 7]
内容的提问来源于stack exchange,提问作者user12741421
相关产品推荐
相关产品推荐

