在Java中创建矩阵

3
我想在Java中创建一个矩阵.. 我已经实现了以下代码
public class Tester {

    public static void main(String[] args) {

        int[][] a = new int[2][0];
        a[0][0] = 3;
        a[1][0] = 5;
        a[2][0] = 6;
        int max = 1;
        for (int x = 0; x < a.length; x++) {
            for (int b = 0; b < a[x].length; b++) {
                if (a[x][b] > max) {
                    max = a[x][b];
                    System.out.println(max);

                }

                System.out.println(a[x][b]);

            }

        }

        System.out.println(a[x][b]);


    }
}

当我运行代码时,出现以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at shapes.Tester.main(Tester.java:8)

我尝试了不同的方法来纠正代码,但都没有起到帮助作用。您能否为我纠正代码?

谢谢


创建一个第二维度为空的2D矩阵并没有任何意义。决定使用一维数组,或者至少每个维度大小为1的二维数组。 - lazary
顺便提一下,你的变量 b 在 for 循环之外是不可见的。 - MGoksu
2个回答

6
当你实例化一个数组时,你给它的是大小而不是索引。因此,要使用第0个索引,你至少需要一个大小为1的数组。
int[][] a = new int[3][1];

这将实例化一个3x1的“矩阵”,意味着第一组方括号的有效索引是0、1和2;而第二组方括号的唯一有效索引是0。这似乎符合你的代码需求。
public static void main(String[] args) {

    // When instantiating an array, you give it sizes, not indices
    int[][] arr = new int[3][1];

    // These are all the valid index combinations for this array
    arr[0][0] = 3;
    arr[1][0] = 5;
    arr[2][0] = 6;

    int max = 1;

    // To use these variables outside of the loop, you need to 
    // declare them outside the loop.
    int x = 0;
    int y = 0;

    for (; x < arr.length; x++) {
        for (; y < arr[x].length; y++) {
            if (arr[x][y] > max) {
                max = arr[x][y];
                System.out.println(max);
            }
            System.out.println(arr[x][y]);
        }
    }

    // This print statement accesses x and y outside the loop
    System.out.println(arr[x][y]);
}

应该用"max = arr[x][y];"而不是"max = arr[x][b];"吧? - Cenk

1
你正在将3个元素存储在第一个数组中。
尝试使用int [][] a = new int [3] [1];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接