java请帮助我完成这个while循环
请纠正我的错误
package com.company;
public class practice2 {
public static void main(String[] args) {
int a = 5;
while (a > 0) {
while (a>0) {
System.out.print("*");
a--;
}
a--;
}
}
}
上面的代码只适用于一个,下面的代码适用于一个。。。。。。。。。为什么我需要将它分配给一个新变量,以便在新循环中使用它
package com.company;
public class practice2 {
public static void main(String[] args) {
int a = 5;
while (a > 0) {
a=b;
while (b>0) {
System.out.print("*");
b--;
}
a--;
}
}
}
要打印:
*****
****
***
**
*
这不是一个家庭作业问题,我只是无法理解这个概念
# 1 楼答案
试试这个
输出:
# 2 楼答案
您的代码现在将打印以下内容:
因为您还没有指定每行需要打印多少次星星
要解决这个问题,只需将
System.out.print("*");
更改为System.out.print("*" * a);
这意味着您需要在每个循环中打印字符
*
“a”次。由于a的值在减小,你的问题就解决了也可以尝试使用for循环而不是while循环。这个website会帮你的
# 3 楼答案
您可以只使用一个循环来执行此操作,并使用
.repeat()
方法来重复星号编辑:调用一个方法来完成这项工作更好:)
输出: