简体   繁体   中英

Print a pyramid/triangle using Scanner

import java.util.Scanner;

public class pyramidMaxSum {

    public static void main(String[] args) {
        int n;
        System.out.println("Enter number of rows: ");
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        System.out.println("Enter numbers:");

        for (int i = 0; i < n; i++) {
            int[] nums = new int[n];
            nums[i] = sc.nextInt();
            for (int j = 0; j < n; j++) {
                System.out.print(" ");
            }
            for (int k = 0; k <= i; k++) {
                System.out.print(nums[i]+" ");
            }
            System.out.println();
        }

    }

}

This is my code.I can't seem to be able to get the desired output,which in turn does not allow me to finish my task.I want to print a pyramid/triangle using the standart input.From this input:

5
5 
10 20
1 3 1
99 20 7 40
5 15 25 30 35

I need to get this output

        5      
      10  20     
    1    3   1   
  99  20   7  40
 5   15  25  30  35

My result is as follows:

5 
 10 10 
 20 20 20 
 1 1 1 1 
 3 3 3 3 3

You need 2 loops: one to input the numbers and one to print the pyramid.

public static void main (String[] args) throws java.lang.Exception
{
    // Get number of rows
    System.out.println("Enter number of rows: ");
    Scanner sc = new Scanner(System.in);
    int numRows = sc.nextInt();

    // Get all the numbers
    System.out.println("Enter numbers:");
    int numNumbers = numRows * (numRows + 1) / 2;
    int [] numbers = new int[numNumbers];
    for (int i = 0; i < numNumbers; i++) {
        numbers[i] = sc.nextInt();
    }

    // Print the pyramid
    for( ..... Leaving this blank as this looks like homework...) {
    }

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