简体   繁体   English

使用扫描仪打印金字塔/三角形

[英]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. 您需要2个循环:一个循环输入数字,一个循环打印金字塔。

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...) {
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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