使用扫描仪

时间:2018-03-14 15:09:29

标签: java java.util.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();
        }

    }

}

这是我的代码。我似乎无法获得所需的输出,这反过来又不允许我完成任务。我想使用标准输入打印金字塔/三角形。这个输入:

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

我需要获得此输出

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

我的结果如下:

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

1 个答案:

答案 0 :(得分:0)

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