我希望用户能够告诉程序他们想要从Pascals三角形中获取多少行,但是我的代码抛出了一个错误,说:“缺少数组维” 这项任务-“您的工作是在多维数组中创建Pascal三角形的前几行,然后将其输出到屏幕上”
import java.util.*;
import java.util.Scanner;
class PascalsTriangle
{
public static void main( String [] args )
{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the amount of rows you want to
be shown: ");
int tri = sc.nextInt();
int [][] triangle = new int[][];
for (int i = 0; i < triangle.length; i++)
{
triangle[i] = new int[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++)
{
triangle[i][j] = triangle[i - 1][j]+triangle[i - 1][j -
1];
}
}
for (int i = 0; i < triangle.length; i++)
{
for (int j = 0; j < triangle[i].length; j++)
{
System.out.print(" "+triangle[i][j]);
}
System.out.println("");
}
}
}
答案 0 :(得分:0)
正如一些评论所说的那样-问题不在于用户输入,而在于数组的初始化。
int [][] triangle = new int[][];
应该类似于:
int [][] triangle = new int[tri][tri * 2];