我可以将循环号模式转换为while循环并执行while循环吗?

问题描述 投票:0回答:2

我正在学习Java循环,并设法使用for循环打印了一个数字模式。我尝试使用while和while循环打印第一模式,但遇到了困难。这是我的代码:

for (int i = 0; i <= 7; i++) {
    for (int j = 0; j <= 4; j++) {
        if ((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
            System.out.print("1");
        else
            System.out.print(" ");
    }

    System.out.println();
}

这是我的while循环代码:

int i = 0, j = 0;
        while (i <= 7) {
            while (j <= 4) {
                if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
                    System.out.print("1");
                else
                    System.out.print(" ");

                j++;
            }

            System.out.println();
            i++;
        }

this is my pattern

java loops for-loop while-loop do-while
2个回答
0
投票

是的,任何for循环都可以转换为while或do-while。

例如:

for(initialize; condition_check, statement1) {
    ......
}

这里statement1 =>通常,这是在condition_check中使用的变量的incrementdecrement

类似的while循环将是:

initialize;
while (condition_check) {
     .......;
     statement1;
}

希望有帮助。


0
投票

在第一个j结束后需要重置j_while计数器

int i = 0, j = 0;
while (i <= 7)
{
//could also reset here
j=0;
while (j <= 4)
{
     if((i == 0 && j > 1) || (i == 1 && j > 0) || (i == 2 && j >= 0) || (i == 3 && j > 1) || (i > 3 && j > 1))
         System.out.print("1");
     else
         System.out.print(" ");
         j++;
       }
       System.out.println();
       i++;
 }
© www.soinside.com 2019 - 2024. All rights reserved.