我写了个杨辉三角的程序,出现数组溢出..
class Yang
{
public static void main(String args[])
{
int i,j;
int Level=10;
int Yang[][]=new int[Level][];
System.out.println( "うぷ杨辉△ ");
for(i=0;i <Yang.length;i++)
Yang[i]=new int[i+1];
Yang[0][0]=1;
for(i=0;i <=Yang.length;i++)
{
Yang[i][0]=1;
for(j=i;j <=Yang[i].length-1;j++)
Yang[i][j]=Yang[i-1][j-1]+Yang[i-1][j];
Yang[i][Yang[i].length-1]=1;
}
for(i=0;i <Yang.length;i++)
{
for(j=0;j <Yang.length;j++)
System.out.println(Yang[i][j]+ " ");
System.out.println();
}
}
}
编译没问题,但运行时数组溢出,如何解决
------解决方案--------------------for(i=0;i <=Yang.length;i++)
{
Yang[i][0]=1;
for(j=i;j <=Yang[i].length-1;j++)
Yang[i][j]=Yang[i-1][j-1]+Yang[i-1][j];
这个地方有问题,上面i初始化为0了,下面i-1不就变成-1了吗,所以
数组越界 推荐使用这种方法
public class YangHui {
public static void main(String args[]) {
final int ROW = 10;//指定输出多少行
int a[][] = new int[ROW + 1][];
for (int i = 0; i <= ROW; i++) {
a[i] = new int[i + 1]; // 指定每行的列数
}
yanghui(a, ROW);
}
static void yanghui(int a[][], int ROW) {
for (int i = 0; i <= ROW; i++)
for (int j = 0; j <= a[i].length - 1; j++) {
if (i == 0 || j == 0 || j == a[i].length - 1)
a[i][j] = 1;
else
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
for (int i = 0; i <= ROW; i++) {
for (int j = 0; j <= a[i].length - 1; j++)
System.out.print(a[i][j] + "\t ");
System.out.println();
}
}
}
------解决方案--------------------按楼主的源代码改写了一下,通过了。楼主试试
class Yang
{
public static void main(String args[])
{
int i,j;
int Level=10;
int Yang[][]=new int[Level][];
System.out.println( "うぷ杨辉△ ");
for(i=0;i <Yang.length;i++)
Yang[i]=new int[i+1];
Yang[0][0]=1;
System.out.println( "ok1 ");
for(i=0;i <Yang.length;i++)
{
Yang[i][0] =1;
Yang[i][i] =1;
}
for(i=2;i <Yang.length;i++)
{
Yang[i][0]=1;
for(j=1;j <Yang[i].length-1;j++)
Yang[i][j]=Yang[i-1][j-1]+Yang[i-1][j];
Yang[i][Yang[i].length-1]=1;
}
System.out.println( "ok ");
for(i=0;i <Yang.length;i++)
{
for(j=0;j <Yang[i].length;j++)
System.out.println(Yang[i][j]+ " ");