-2

我想问一个已经磨碎 ja 的代码问题,我有以下代码,我正在通过一个 10x5 数组来填充数字 1,到 49 来填充原语,负责制作票证的函数给了我非常罕见的错误。Index On Bound 理论上该功能不会被排除在外,但如果有人可以打我,我不知道该怎么办。

// It is this part that gives me an error, I have a fly
            int ,c=0;
            int m[][]= new int[10][5];
    
            for (int i=0;i<m.length;i++) {
                for (int x=0;x<m.length;x++,i++) {
                    m[x][i]=c;
                    
                }
                
            }
            
            
            
// This part of code I only have to check if the data output
    // does them correctly
            for(int i=0;i<m[0].length;i++) {
                for(int x=0;x<m.length;x++) {
                    System.out.print(" "+m[i][x]+" ");
                }
                System.out.println(" ");
            }
        }
    
    El error que me da es siguiente:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
        at provas/provas.main.main(main.java:11)
4

1 回答 1

0

看起来你想用来自的数字填充给定的数组1 to 49。所以你要注意:

  • int[][] arr = new int[10][5]用and创建一个int数组10 rows5 columns
  • arr.length给你一个总rows amount
  • arr[0].length给你一个总数columns amountrow 0 每行可能有不同的长度)
public static int[][] fillArray(int[][] arr) {
    int i = 1;

    for (int row = 0; row < arr.length; row++)
        for (int col = 0; col < arr[row].length; col++)
            arr[row][col] = i++;

    return arr;
}

最后打印一个数组:

public static void printArray(int[][] arr) {
    for (int row = 0; row < arr.length; row++) {
        for (int col = 0; col < arr[row].length; col++)
            System.out.format("%3d", arr[row][col]);

        System.out.println();
    }
}

你原来的方法可能是这样的:

int[][] arr = fillArray(new int[10][5]);
printArray(arr);
于 2021-02-02T22:43:06.747 回答