我想做一個數組,輸出模式取決於我給它的輸入有多少行和列,並且當它到達第三個方法時收到一個錯誤。我明白,數組開始於索引零,如果我輸入(0 0)的矩陣它的界限,但我不知道如何解決這個問題。感謝您的幫助!繼續收到ArrayIndexOutOfBoundsException
這裏是我的第一類代碼:
public class Transpose {
public static int [][] createPatterned2DArray(int rows, int cols)
{
int [][] table = new int [rows] [cols];
for (int numRows = 0; numRows < table.length; numRows++){
for (int numCols = 0; numCols < table[0].length; numCols++){
table [numRows][numCols] = 10 + rows*(numRows +1) + numCols;
}
}
return table;
}
public static void print2DArray (int[][] matrix)
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
System.out.printf("%-4d",matrix[row][col]);
}
System.out.println();
}
}
public static void print2DArrayTransposed(int [][] matrix)
{
for (int row = 0; row < matrix[0].length; row++)
{
for (int col = 0; col < matrix.length; col++)
{
//try {
// if (matrix[0] == 0) {
// System.out.println(matrix[0][0]);
// throw new Exception();
System.out.printf("%-4d",matrix [col][row]);
// }
//catch (Exception e){
// System.out.print(e);
}
System.out.println();
}
}
}
這裏是第二類:
import java.util.*;
public class TestTranspose extends Transpose {
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
int rows = scan.nextInt();
int cols = scan.nextInt();
int [][] table = createPatterned2DArray(rows,cols);
print2DArray(table);
System.out.println();
print2DArrayTransposed(table);
System.out.println();
}
}
這是我得到的錯誤和它的駕駛我瘋了! 我似乎無法包裹我的頭如何拋出異常或使輸出顯示什麼都沒有,當我輸入數組的輸入(0 0)。我怎樣才能糾正這一行不會讓我輸出(0 0)的數組?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Transpose.print2DArrayTransposed(Transpose.java:32)
at TestTranspose.main(TestTranspose.java:13)
非常感謝你!我有一些沿線的東西,但我可以不知道爲我的生活:) – pitonface69