简体   繁体   English

将for循环的示例转换为while循环

[英]Converting an example for loop to a while loop

I am just beginning to code java, and I found an example of a nested loop which then asks to convert it to a while statement. 我刚刚开始编写Java代码,并且发现了一个嵌套循环的示例,然后要求将其转换为while语句。 I am struggling to figure out how to convert it so the output is the same, any help on this would be greatly appreciated. 我正在努力找出如何转换它,以便输出是相同的,对此的任何帮助将不胜感激。

public static void main(String[] args) {

   for (int j = 0; j < 10; j++) {

         for (int i = j; i < 10; i++) {
           if (i == j) {
             for (int k = 0; k < j; k++) {
               System.out.print("  ");
             }
           }
           System.out.print(" " + i);
         }
         System.out.println();
       }

This is what I have gotten to after trying, but my output is still formatted incorrectly. 这是尝试后得到的,但是我的输出仍然格式错误。

    int j = 0;
    while (j < 10) { 
        j++;

        int i = j;
        while (i < 10) {
            i++;

            if (i == j) {

                int k = 0;
                    while(k < 10) {
                    k--;

                System.out.print(" ");
                }   
            }
            System.out.print(" " + j);
        }
        System.out.println();
    }
}

You were so close! 你好亲密!

1. while(k<10) should be while(k< j)` (Also it should be k++ not k--) 1. while(k<10) should be while(k <j)`(也应该是k ++而不是k--)

  1. Move the increments to the bottom of the loops instead of at the top. 将增量移动到循环的底部而不是顶部。

  2. In the while(k<j) loop you should print out two spaces instead of one. while(k<j)循环中,您应该打印出两个空格而不是一个空格。

code: 码:

        int j = 0;
        while (j < 10) { 


            int i = j;
            while (i < 10) {


                if (i == j) {

                    int k = 0;
                    while(k < j) {

                        System.out.print("  ");
                        k++;
                    }   
                }
                System.out.print(" " + i);
                i++;
            }
            System.out.println();
            j++;
        }

output: 输出:

0 1 2 3 4 5 6 7 8 9
  1 2 3 4 5 6 7 8 9
    2 3 4 5 6 7 8 9
      3 4 5 6 7 8 9
        4 5 6 7 8 9
          5 6 7 8 9
            6 7 8 9
              7 8 9
                8 9
                  9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM