如何使用嵌套 for 循环来创建行以向 Java 中的每一行添加一个额外的列?

How do I use nested for loops to create rows that add an additional column to each row in Java?

我正在参加 CS class,我的老师刚刚教了我们 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();
        }
      }
    }

如有任何帮助,我将不胜感激。

你必须使用第一个循环的row,在第二个循环中,将row的初始值设置为3,使第一个循环打印til 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 = 1 迭代到 row = 3,依此类推。