我的数组在哪里越界



我看过其他关于越界错误的问题并理解它们,无法理解这段代码中的错误。

问题:一个 JAVA 程序,它将读取对应于关系 R 的布尔矩阵,并输出 R 是自反的、对称的、反对称的和/或传递的。程序的输入将是 n x n 布尔矩阵的大小 n,后跟矩阵元素。

在输入关系无法具有特定属性的情况下,程序必须输出原因。

解决方案:我已经提供了代码,它在主行和第 65 行抛出"java.lang.ArrayIndexOutOfBoundsException"错误。我看不到我的数组是如何越界的

错误:线程"main"中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at XYZ.BooleanMatrix.main(BooleanMatrix.java:65)

法典:

package XYZ;
import edu.princeton.cs.algs4.*;
public class BooleanMatrix {
// read matrix from standard input
public static boolean[][] read() {
    int n = StdIn.readInt();
    boolean[][] a = new boolean[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (StdIn.readInt() != 0)
                a[i][j] = true;
        }
    }
    return a;
}
// print matrix to standard output
public static void print(boolean[][] a) {
    int n = a.length;
    StdOut.println(n);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i][j])
                StdOut.print("1 ");
            else
                StdOut.print("0 ");
        }
        StdOut.println();
    }
}
// random n-by-n matrix, where each entry is true with probability p
public static boolean[][] random(int n, double p) {
    boolean[][] a = new boolean[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            a[i][j] = StdRandom.bernoulli(p);
        }
    }
    return a;
}
// display the matrix using standard draw
// depending on variable which, plot true or false entries in foreground
// color
public static void show(boolean[][] a, boolean which) {
    int n = a.length;
    StdDraw.setXscale(0, n - 1);
    StdDraw.setYscale(0, n - 1);
    double r = 0.5;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i][j] == which) {
                StdDraw.filledSquare(j, n - i - 1, r);
            }
        }
    }
}
// test client
public static void main(String[] args) {
    int n = Integer.parseInt(args[0]); //LINE 65
    double p = Double.parseDouble(args[1]);
    boolean[][] a = random(n, p);
    print(a);
    show(a, true);
}}

我不知道StdDraw.setXscale(0, n - 1);的确切工作,但我认为它创建了一个包含 n-1 行的表。 因此,如果您尝试用 N 行填充它,则会出现越界错误。 尝试在第 47 行中使用它:

StdDraw.setXscale(0, n);
StdDraw.setYscale(0, n);

如您帖子下方的评论中所述:如果您在调用程序时未输入任何参数,您将获得越界异常,因为程序期望在 aray 中提供参数并且没有任何参数。

要提供参数,请打开命令行并调用/java yourcompiledjavafile arg[0] arg[1]

最新更新