java - 尝试打印三角形的错误输出
问题描述
我试图打印一个图案
* * * * *
* * * *
* * *
* *
*
我用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");
}
}
}
此外,您似乎对编程很陌生,所以我添加了一些小建议来编写“更好的代码”
推荐阅读
- ios - 无法在 iPad Air 上安装企业应用程序
- angular - 带有url参数的Angular2路由
- javascript - 在对象解构中使用冒号
- sql - 选择分页连接的行以达到不同相关行的可靠限制
- c - 如何告诉 Linux 进程将文件用作其整个堆?
- ios - 方法不会覆盖其超类中的任何方法:Swift/UITableViewController/MapKit
- php - 多表查询(获取注册详情)
- python - 为什么我的 python/pandas 代码没有正确过滤终止日期?
- javascript - div标签下的元素完全加载后如何隐藏加载器
- nginx - 如何通过缓存请求到后端(清漆服务器)实现清漆服务器的负载平衡?