這是我以順時針螺旋列印從 1 到 N^2 的自然數的程式。我收到以下錯誤
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -2147483648
out of bounds for length 3
at Spiral.main(Spiral.java:13)
這是我的程式
class Spiral{
public static void main(String[] args) {
System.out.println("Enter value of N");
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int arr[][]=new int[N][N];
int r1=0, c1=0, r2=N-1, c2=N-1, flag=1; int i=0,j=0;
while(flag<=N*N)
{ for(j=c1;j<=c2;j )
arr[r1][j]=flag ;
for( i=r1 1;i<=r2;i )
arr[i][c2]=flag ; //this is the line of error
for(j=c2-1;j>=c1;j--)
arr[r2][j]=flag ;
for(i=r2-1; i>r1 1;i--)
arr[i][c1]=flag ;
r1 ; r2--; c1 ; c2--;
}
System.out.println("The Circular Matrix is:");
for( i=0;i<N;i )
{
for( j=0;j<N;j )
{
System.out.print(arr[i][j] "\t");
}
System.out.println();
}
}
}
該代碼在 N=2 時作業正常,但在 N=3,4 等情況下開始出現此錯誤。如果 N=3,則 arr[i][c2] 的最大值將是 arr[2][2],它落在3x3 矩陣的范圍。有人可以解釋為什么我會收到這個錯誤嗎?
uj5u.com熱心網友回復:
在相應的 for 回圈之后而不是在 while 回圈結束時適當地增加/減少r1、c2、r2和c1:
import java.util.Scanner;
class Spiral {
public static void main(String[] args) {
System.out.println("Enter value of N");
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[][] arr = new int[N][N];
int r1 = 0, c1 = 0, r2 = N - 1, c2 = N - 1, flag = 1;
int i = 0, j = 0;
while (flag <= N * N) {
for (j = c1; j <= c2; j )
arr[r1][j] = flag ;
r1 ;
for (i = r1; i <= r2; i )
arr[i][c2] = flag ;
c2--;
for (j = c2; j >= c1; j--)
arr[r2][j] = flag ;
r2--;
for (i = r2; i >= r1; i--)
arr[i][c1] = flag ;
c1 ;
}
System.out.println("The Circular Matrix is:");
for (i = 0; i < N; i ) {
for (j = 0; j < N; j ) {
System.out.print(arr[i][j] "\t");
}
System.out.println();
}
}
}
示例用法 1:
Enter value of N
4
The Circular Matrix is:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
示例用法 2:
Enter value of N
7
The Circular Matrix is:
1 2 3 4 5 6 7
24 25 26 27 28 29 8
23 40 41 42 43 30 9
22 39 48 49 44 31 10
21 38 47 46 45 32 11
20 37 36 35 34 33 12
19 18 17 16 15 14 13
uj5u.com熱心網友回復:
在 dugger 中,您可以看到在第二個 fpr 回圈中有一個 IndexOutOfBoundsException,因為 i 是 3。 int 最大值然后溢位。你 for 回圈錯了
uj5u.com熱心網友回復:
如果根據您的邏輯start row大于end row或start col大于,您需要退出end col。
將此添加到您的while回圈中
if (r1 > r2 || c1 > c2) break;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383234.html
上一篇:提取符合條件的最后一項
下一篇:使用索引從物件陣列中洗掉物件?
