java反向三角形星型图案

huangapple go评论58阅读模式
英文:

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&lt;=5){
    while (j&gt;=i){
        System.out.print(&quot;*&quot;);
        j--;
    }
    System.out.print(&quot;\n&quot;);
    i++;
}

image attached

答案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&lt;=5){
    j = 5;
    while (j&gt;=i){
        System.out.print(&quot;*&quot;);
        j--;
    }
    System.out.print(&quot;\n&quot;);
    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&lt;size){
    while (remaining&gt;linesPrinted){
        System.out.print(&quot;*&quot;);
        remaining--;
    }
    System.out.print(&quot;\n&quot;);
    linesPrinted++;
    remaining=size;
}

huangapple
  • 本文由 发表于 2020年10月5日 20:49:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64208951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定