【问题标题】:Como soluciono siguiente error java.lang.ArrayIndexOutOfBoundsExceptionComo soluciono siguiente 错误 java.lang.ArrayIndexOutOfBoundsException
【发布时间】:2021-05-07 03:40:34
【问题描述】:

我想问一个已经磨碎 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)

【问题讨论】:

  • 请用英文!
  • 我投票结束这个问题,因为它不是英文的
  • 对不起各位,我需要你们帮忙

标签: java exception arrayindexoutofboundsexception


【解决方案1】:

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

  • int[][] arr = new int[10][5] 使用 10 rows5 columns 创建一个 int 数组
  • arr.length 给你一个总数 rows amount
  • arr[0].length 给你一个总数 columns amount row 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多