尝试打印三角形时输出错误



我试着打印一个图案

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

我用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();
}
}
}

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

预期输出:

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

你的代码很好,只是在第一个循环之后去掉分号所以应该是:

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");
}
}
} 

而且看起来你对编程很陌生,所以我添加了一些建议来编写"更好的代码">

最新更新