尝试构建pascal三角形(JAVA)时,多次数组初始化错误
我正在尝试编写一个类,该类使用多维数组创建pascal三角形的对象。现在我已经准备好了一切(至少我认为是这样),除了数组的正确初始化。我的程序如下:尝试构建pascal三角形(JAVA)时,多次数组初始化错误,java,multidimensional-array,initialization,pascals-triangle,Java,Multidimensional Array,Initialization,Pascals Triangle,我正在尝试编写一个类,该类使用多维数组创建pascal三角形的对象。现在我已经准备好了一切(至少我认为是这样),除了数组的正确初始化。我的程序如下: class Pascal{ //Object variables int size; int[][] pascal; Pascal(int size){ //Constructor this.size = size; //Defines how many rows/columns the triangle has. pasca
class Pascal{
//Object variables
int size;
int[][] pascal;
Pascal(int size){ //Constructor
this.size = size; //Defines how many rows/columns the triangle has.
pascal = new int[size][];
//Allocation of the arrays
for(int i=0;i<pascal.length;i++)
pascal[i] = new int[i+1];
pascal[0][0] = 1; //the tip of the triangle is always one. Also you need a value to start with.
//Initialisation of the elements
for(int x=0;x<pascal.length;x++){
for(int y=0;y<pascal[x].length;y++){
if(x>0){
if(y==0 || y == (pascal[x].length)-1)
pascal[x][y] = 1; //Initialisation of the first and last element of the actual array x
else
pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//Initialisation of all elements in between
}
}
}
}
//The print method needed to display the pascal triangle
void print(){
for(int i=0;i<pascal.length;i++){
for(int k=pascal.length;k>i;k--)
System.out.print(" ");
for(int j=0;j<pascal[i].length;j++)
System.out.print(pascal[i][j]+" ");
System.out.println();
}
}
//main function
public static void main(String... args){
Pascal p = new Pascal(5); //example triangle consisting of 5 rows total
p.print();
}
}
但事实是:
1
2 1
1 1 1
1 0 1 1
1 0 0 0 1
我知道问题一定在代码的数组初始化部分的某个地方,这可能是一个简单的错误,但是盯着监视器看我再也看不到任何地方了:/
以防你不想给我答案:
根据我的理解,数组元素pascal[1][0]应该是1而不是2,因为当for循环的值x为1且值y为0时,if条件if(y==0 | | y==pascal[x].length-1)应该适用,从而设置pascal[1][0]=1
谢谢你的帮助 在构造函数中,初始化2D数组时,在
else
中,您的赋值不正确。您想初始化当前元素,但左侧不正确(并且与if
不一致):
尝试[x][y]
元素本身
pascal[x][y] = pascal[x-1][y] + pascal[x-1][y-1];
仅进行此更改,即可获得正确的输出:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
就在这一秒,我得到了同样的结果。一定是时候来了。谢谢你的快速回答。那个问题真是浪费了网络空间-_-
pascal[x][y] = pascal[x-1][y] + pascal[x-1][y-1];
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1