gpt4 book ai didi

java - 如何使用嵌套 for 循环来创建向 Java 中的每一行添加附加列的行?

转载 作者:行者123 更新时间:2023-12-01 21:34:26 25 4
gpt4 key购买 nike

我正在上计算机科学类(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,让第一个循环打印到 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 等等。

关于java - 如何使用嵌套 for 循环来创建向 Java 中的每一行添加附加列的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58806920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com