简体   繁体   中英

Program won't let the user input the number of rows in Pascal's triangle - Java

I want the user to be able to tell the program how many rows they want from the Pascals triangle but my code throws back an error saying- "array dimension missing' This the task- "Your job is to create the first few rows of Pascal's triangle in a multidimensional array and then output it to the screen"

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("");
        }

    }
}

As some of the comments have said -- the problem isn't with your user input, it's with your initialization of the array.

int [][] triangle = new int[][];

Should probably be something like:

int [][] triangle = new int[tri][tri * 2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM