2017-10-17 61 views
-1

我看過其他有關越界錯誤的問題並理解它們,無法理解此代碼中的錯誤。我的陣列在哪裏出界?

問題:JAVA程序將讀取與關係R對應的布爾矩陣,並輸出R是否自反,對稱,反對稱和/或傳遞。程序的輸入將是n×n布爾矩陣的大小n,後跟矩陣元素。

程序在輸入關係不具有某個屬性的情況下必須輸出一個原因。

解決方案:我所提供的代碼,它拋出了「java.lang.ArrayIndexOutOfBoundsException」錯誤在主線路65我看不到我的陣列是如何出界

ERROR: Exception in thread "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); 
}} 
+2

和什麼是65行? – Stultuske

+0

你指定了參數嗎? –

+0

請在您的問題中提供完整的堆棧放棄。 – AxelH

回答

0

我不知道的StdDraw.setXscale(0, n - 1);確切的工作,但我認爲它會創建一個表,N-1行。所以如果你嘗試用n行填充它,會出現一個界限錯誤。嘗試在47行使用此:

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

正如下面的文章的評論中指出:如果你鴕鳥政策輸入任何參數調用程序時you'll得到一個出界異常,因爲程序在預計參數阿里,沒有任何。

提供參數打開命令行並調用/ java yourcompiledjavafile arg [0] arg [1]

+0

這可能是一個好主意,但我不認爲這是異常的原因 –

+0

我試着改變很多值,但沒有奏效。我如何提供主要的參數? – user4127994

+0

我在終端窗口中試過這個命令,它說沒有找到這樣的文件或目錄。我是否要進入某個目錄然後執行命令? 我可以添加一個try-catch嗎? – user4127994