2012-11-08 50 views
1

我有這個代碼,但我不斷收到此錯誤消息,我不知道爲什麼?線程「主」java.lang.ArrayIndexOutOfBoundsException異常的錯誤消息:

異常在線程 「主」 java.lang.ArrayIndexOutOfBoundsException:2 在 javaapplication28.JavaApplication28.main(JavaApplication28.java:38)1 2 Java結果:1

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 
     System.out.println("This program transposes a matrix."); 
     System.out.println("Please enter the number of rows"); 
     int rows = input.nextInt(); 
     System.out.println("User enters: "+rows); 
     System.out.println("Please enter the number of columns"); 
     int columns = input.nextInt(); 
     System.out.println("User enters: "+columns); 
     int [][]matrix=new int[rows][columns]; 
     for(int i=0;i<matrix.length;i++){ 
      for(int j=0;j<matrix[i].length;j++){ 
      System.out.print("Enter value for row [" +i+ "] column [" +j+"]:"); 
       matrix[i][j]=input.nextInt(); 
      } 
     } 
     for(int i=0;i<=matrix.length;i++){ 
      System.out.println(); 
      for(int j=0;j<=matrix.length;j++){ 
       System.out.print(matrix[i][j]+" ");   
      } 
     } 
     System.out.println("The transpose of this matrix has" +columns+"rows and"+rows+"columns and the transpose is:"); 
     for(int i=0;i<=matrix.length;i++){ 
      System.out.println(); 
      for(int j=0;j<=matrix.length;j++){ 
       System.out.print(matrix[j][i]+" "); 
    } 
}} 
} 

回答

3

你運行循環從0到長度+ 1 i<=matrix.length。從for聲明中刪除=並在內部循環中添加:matrix[i].length而不是matrix.length以獲得列計數而不是行。

這裏是合法的代碼:

for(int i=0;i<matrix.length;i++){ 
     System.out.println(); 
     for(int j=0;j<matrix[i].length;j++){ 
      System.out.print(matrix[i][j]+" ");   
     } 
    } 
    System.out.println("The transpose of this matrix has" +columns+"rows and"+rows+"columns and the transpose is:"); 
    for(int i=0;i<matrix.length;i++){ 
     System.out.println(); 
     for(int j=0;j<matrix[i].length;j++){ 
      System.out.print(matrix[j][i]+" "); 
     } 
    }} 
+0

對於一般情況(不規則數組),不應該是'j

+0

另外,轉置代碼是錯誤的,除非矩陣總是正方形,否則不能像一般情況下那樣交換索引。 –

+0

@JimGarrison好吧,如果你進入第二'for'i = 0;所以你可以使用'i'或'0'。一樣的東西。誠然,使用索引不是好技術。對於這個例子他有方矩陣。否則我可以用其他方式寫。 –

0

如果你從0開始你for週期指標的迭代器,你應該使用<而不是<=當它是一個數組的長度,否則這將是,如果你」重新嘗試獲取(大小爲n)數組的第(n + 1)個元素是什麼導致ArrayIndexOutOfBoundsException例外

相關問題