以不同的数字开始,在Java中生成一个数字图案
我正在准备编程考试。而且我陷入了这项任务,我了解模式的逻辑(,至少我认为),但我不知道如何解决这个问题。
输入的输出a = 6
需要如下:
012345
123456
234567
345678
456789
567890
输入a = 3
需要如下:
012
123
234
输入a = 4
需要就像:
0123
1234
2345
3456
但是我明白了:
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
这是我的代码:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6
needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3
needs to be like :
012
123
234
Output for input a = 4
needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要进行这些更改以获取所需的输出:
的终止条件应为
i&lt;
;循环的内部
的终止条件应为
j&lt; a + i
;您要打印的号码不应该是
j
,而是j%10
满足您已提供的数据样本(对于输入a = 6 < /code>它打印
0
作为最后一行中的最后一个数字,而不是10
,这意味着我们不需要j
,而只需要最右数是10
的其余部分。这就是可以修复的方式:
You need to make these changes to get the required output:
Termination conditions of the outer
for
loop should bei < a
;Termination conditions of the inner
for
loop should bej < a + i
;The number you're printing should be not
j
butj % 10
to satisfy the data sample you've provided (for inputa=6
it prints0
as the last number on the very last line instead of10
, that means we need notj
, but only its rightmost digit which is the remainder of division by10
).That's how it can be fixed:
观察:
由于它是2维输出,因此我们需要2个循环(一个内部循环)。
同样,每行的起点是最后一行启动+1的值。
如果值交叉10,则我们将仅保留单位数字值(如最后一行中)。 (因此,我们使用有助于提取单位数字的模量运算符%)
代码:
答案是:
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
and the answer is :