1

我的代码有什么问题?我正在尝试传递两个参数(一个用于随机种子,另一个用于 the 并且我得到数组我们的边界异常错误..我不明白我做错了什么..我感谢任何帮助

import java.util.Random;

public class sparse {

    public static int size;
    public static int matrix[][] = new int[size][size];
    public static int seed;

    public static void main(String args[]) {

        seed = Integer.parseInt(args[0]);
        size = Integer.parseInt(args[1]);

        matrix = matrixGen();
    }

    public static int[][] matrixGen() {
        Random r = new Random(seed);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = r.nextInt(100);
            }
        }

        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print(" " + matrix[i][j]);
            }
            System.out.println("  ");
        }

        return matrix;
    }
}
4

3 回答 3

4

您收到错误是因为您在仍然为零matrix的时候分配了 :size

public static int matrix[][] = new int[size][size]; // size is zero here

main()您需要从声明中删除初始化,并在阅读sizefrom后将其移至args.

public static void main(String args[]) {
    seed = Integer.parseInt(args[0]);
    size = Integer.parseInt(args[1]);
    matrix = new int[size][size];
    matrix = matrixGen();
}
于 2013-03-09T22:14:44.260 回答
2

您必须在为其分配空间之前初始化矩阵的大小:

 public static int size = 30; // or whatever value do you want
于 2013-03-09T22:13:24.237 回答
0

初始化矩阵字段时,静态字段种子和大小具有默认值 (0)。

因此矩阵是一个 0x0 数组,没有任何元素的空间:任何访问都会给出这样的异常。

To fix, you should set the matrix field in the main function, after arguments' parse.

于 2013-03-09T22:19:40.200 回答