java - 如何使用嵌套的 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();
}
}
}
我很感激这方面的任何帮助。
解决方案
您必须row
在第二个循环中使用第一个循环,并设置 to 的初始值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
til迭代row = 3
,依此类推。
推荐阅读
- sql-server - 识别行中不匹配的记录 - SQL Server
- solr - Hybris如何在SOLR中索引变体
- google-colaboratory - Google Colab 中的 Meshroom 但没有输出文件
- multithreading - 无法让 Asyncio 并行运行 2 个任务(在等待下一个查询完成时处理查询结果)
- java - 片段从一开始就没有显示 | 安卓工作室
- html - 文本区域背景颜色在 chrome 中有效,但在 Firefox 中无效
- visual-studio-code - 是否可以通过集成终端获取您在 VS Code 中打开/正在查看的文件的完整文件名?
- angular - Flatpickr 不会以角度反应形式修补我的价值
- linux - 使用 Alpine Linux 的 Docker 映像:肯定存在可执行文件,但在尝试执行时找不到
- php - 使用邮递员发送 POST 请求,但在 php 中接收 GET 请求。我尝试使用邮递员创建 API