首页 > 解决方案 > 尝试打印三角形的错误输出

问题描述

我试图打印一个图案

* * * * *
* * * * 
* * *
* *
*

我用java写了这段代码

public class Psttr {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner h=new Scanner(System.in);
        int n=h.nextInt();
        int x=n;
        int i=1;
        
        for( i=1;i<=n;i++);
        {
            for(int j=1;j<=x;j++) {
                System.out.print("*");  
            }
            x=x-1;
            System.out.println();
        }

    }

}

我没有得到正确的输出,总是*****

预期输出:

* * * * *
* * * * 
* * *
* *
*

标签: java

解决方案


您的代码很好,只需在第一个循环后去掉分号,这样就可以了:

public class Psttr {

    public static void main(String[] args) {
        Scanner h=new Scanner(System.in);
        int n=h.nextInt();
        int x=n;
        for(int i=1;i<=n;i++){ // You can init "i" here
            for(int j=1; j<=x--; j++) {
                System.out.print("*");
            }
            x--; // You can use post-decrement (or pre, it's the same here)
            System.out.print("\n");
        }
    }
} 

此外,您似乎对编程很陌生,所以我添加了一些小建议来编写“更好的代码”


推荐阅读