如何改进此代码以打印数字三角形?

时间:2017-11-14 16:44:25

标签: java

我是初学者,刚刚开始编码。我写了这个得到下面提到的输出,也得到了一个结果。但我觉得我的代码效率不高,有人可以告诉我如何写得更好吗?

    1
   22
  333
 4444
55555
package basic;

import java.util.Scanner;

public class Pattern {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the number of rows?");
        int n = scan.nextInt();

        int num1 = 1;

        for (int i = 1; i <= n; i++) {
            for (int k = n - 1; k >= i; k--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print(num1);
            }
            System.out.println();
            num1 = num1 + 1;

        }

    }
}

1 个答案:

答案 0 :(得分:1)

改善建议

  • 您的num1变量是不必要的
  • 循环不必要。

    package basic;
    
    import java.util.Scanner;
    
    public class Pattern {
    
    public static void main(String[] args) {
    
        Scanner scan = new Scanner(System.in);
    
        System.out.println("Enter the number of rows of the pyramid?");
        int n = scan.nextInt();
    
        for (int i = 1; i <= n; i++) {
            for (int j=1; j<=n;j++){
                if (j <= n-i){
                    System.out.print(" ");
                }else{
                    System.out.print(i);
                }
            }
            System.out.println()
        }
    
    }
    

输出:当输入为5时

**** 1

*** 22

** 333

* 4444

55555