首页 > 解决方案 > 如何使用嵌套的 for 循环来创建在 Java 中为每一行添加额外列的行?

问题描述

我正在上 CS 课,我的老师刚刚教我们 Java 中的嵌套 for 循环。

我的代码的最终结果是:

1234567
1234567
1234567
1234567
1234567

但我的老师想要的是:

123
1234
12345
123456
1234567

这是我的代码:

public class NestedLoop2
    {
      public static void main(String[] args)
      {
        for(int row = 1; row <= 5; row++)
        {
          for(int column = 1; column <= 7; column++)
          {

            System.out.print(column);

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

我很感激这方面的任何帮助。

标签: javanested-loops

解决方案


您必须row在第二个循环中使用第一个循环,并设置 to 的初始值row3以使第一个循环打印到3,如下所示:

public class NestedLoop2
    {
      public static void main(String[] args)
      {
        // The loop begins in row 3, because the first example is: 123
        // And the row will iterate till the 7, to print 5 rows
        for(int row = 3; row <= 7; row++)
        {
          // This loops always begins from 1 and
          // will iterate till the row, to increase the columns
          // Example: 1°: 123, 2°: 1234, etc
          for(int column = 1; column <= row; column++)
          {

            System.out.print(column);

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

因此,在内部循环中,它将在第一个循环中打印:123,因为它从column = 1til迭代row = 3,依此类推。


推荐阅读