英文:
java reverse triangle star pattern
问题
以下是翻译好的内容:
使用for循环很容易打印,但我想使用while循环打印,但我无法做到,而且在这段代码中也看不到任何错误:
int i, j;
i = 1;
j = 5;
while (i<=5){
while (j>=i){
System.out.print("*");
j--;
}
System.out.print("\n");
i++;
}
英文:
It is easy to print using for loop but I want to print it using while loop but I am unable to do so and also can't see any mistake in this:
int i, j;
i = 1;
j = 5;
while (i<=5){
while (j>=i){
System.out.print("*");
j--;
}
System.out.print("\n");
i++;
}
答案1
得分: 5
你需要在外部循环中重置变量 j
的值,即:
int i, j;
i = 1;
while (i <= 5){
j = 5;
while (j >= i){
System.out.print("*");
j--;
}
System.out.print("\n");
i++;
}
英文:
You need to reset the value of j
in the outer loop i.e.
int i, j;
i = 1;
while (i<=5){
j = 5;
while (j>=i){
System.out.print("*");
j--;
}
System.out.print("\n");
i++;
}
答案2
得分: 0
如@Turamarth所提到的,您应该在外部循环中重置j的值:
final int size = 5;
int linesPrinted = 0;
int remaining = size;
while (linesPrinted < size) {
while (remaining > linesPrinted) {
System.out.print("*");
remaining--;
}
System.out.print("\n");
linesPrinted++;
remaining = size;
}
[1]: https://stackoverflow.com/users/5457643/turamarth
英文:
As mentionned by @Turamarth, you should reset the value of j in the outer loop:
final int size = 5;
int linesPrinted = 0;
int remaining = size;
while (linesPrinted<size){
while (remaining>linesPrinted){
System.out.print("*");
remaining--;
}
System.out.print("\n");
linesPrinted++;
remaining=size;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论