我正在上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();
}
}
}
如果有人帮我,我将不胜感激。
您必须在第二个循环中使用第一个循环的row
,并将row
的初始值设置为3
,以使第一个循环打印到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
,依此类推