[英]Java Index Out Of Bounds Error on Pascal Triangle
I have to create a Pascal Triangle and when I run the code, it gives me an Array out Of Bounds Error. 我必须创建一个Pascal Triangle,当我运行代码时,它给我一个数组超出范围错误。 Please Help.
请帮忙。 I guess I have used a good logic but am unable to get the result.
我想我使用了一个很好的逻辑,但我无法得到结果。
import java.io.*;
public class Question_4
{
public static void main (String[] args)throws IOException
{
System.out.println("Enter the value of N");
InputStreamReader x = new InputStreamReader (System.in);
BufferedReader y = new BufferedReader (x);
int n = Integer.parseInt (y.readLine ());
int ar [] [] = new int [n] [(2*n)-1];
int previous = 0;
int next = 0;
int se = 0;
for (int row = 0 ; row<n ; row++)
{
se = (n - row) - 1;
for (int column = 0 ; column < ((2*n)-1) ; column ++)
{
try
{
previous = ar [row-1] [column+1];
next = ar [row-1] [column +3];
}
finally
{
if (column < se)
ar [row] [column] = 0;
else if (column > (n-se))
ar [row] [column] = 0;
else if (row == 0 || row == 1)
ar [row] [column] = 1;
else
ar [row] [column] = (previous + next);
}
}
}
for (int i = 0;i<n;i++)
{
for (int j = 0; j<((2*n)-1);j++)
System.out.print (ar [i] [j]);
System.out.println ();
}
}
}
The problem within the this line: 此行中的问题:
previous = ar [row-1] [column+1];
At the first time of the outer loop, the row value is 0
, so 0 - 1
is -1
, which is invalid position the array. 在第一次外部循环时,行值为
0
,所以0 - 1
为-1
,这在数组的无效位置。
You declared this array: 你声明了这个数组:
int ar [] [] = new int [n] [(2*n)-1];
Then you have this loop: 然后你有这个循环:
for (int column = 0 ; column < ((2*n)-1) ; column ++)
Which means that column will at some point be equal to the index of the last cell in ar[][]. 这意味着该列在某些时候将等于ar [] []中最后一个单元格的索引。 And in your loop you call:
在你的循环中你打电话:
previous = ar [row-1] [column+1];
next = ar [row-1] [column +3];
That is why you get indexOutOfBoundsException. 这就是你得到indexOutOfBoundsException的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.