我正在編寫代碼以在以 n 值的形式獲取用戶輸入時打印矩陣:假設如果 n= 3 輸出:3 3 3 3 0 3 3 1 3 3 2 3 3 3 3我在行中收到 ArrayIndexOutOfBoundException: a[i][j]=n;import java.util.*;public class HelloWorld{ public static void main(String []args){ Scanner scan = new Scanner(System.in); //System.out.println("Enter n"); int n = scan.nextInt(); System.out.println(n); int a[][]= new int[n][n]; int b=0; int mid = n/2 +1; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i+j==mid) { a[i][j]=n-b; b++; } else { a[i][j]=n; } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(a[i][j]); } System.out.println(); } }}
3 回答

叮當貓咪
TA貢獻1776條經驗 獲得超12個贊
如果請求一個負數或一個大于或等于數組大小的索引,則 JAVA 會拋出一個 ArrayIndexOutOfBounds 異常。這與不進行綁定檢查索引的 C/C++ 不同。TheArrayIndexOutOfBoundsException 是僅在運行時拋出的運行時異常。
添加回答
舉報
0/150
提交
取消