[英]Java, pyramid of numbers
I know there is a lot of threads about this easy task, but I still need to put an extra for loop somewhere. 我知道有许多关于此简单任务的线程,但是我仍然需要在某个地方放置一个额外的for循环。
Thus far, I managed to do this: 到目前为止,我设法做到了:
public static void trikotnik(int n){
for (int i = 1; i <= n; i++ )
{
for (int j = 1; j < n; j++ )
System.out.print(" ");
n--;
for (int k = 1; k <= 2*i - 1; k++ )
System.out.print(k);
System.out.println("");
}
}
which outputs a nice pyramide (ignore format, i dunno how to do it properly). 它输出一个不错的金字塔(忽略格式,我不知道如何正确执行此操作)。
1 1
1 2 3 1 2 3
1 2 3 4 5 1 2 3 4 5
1 2 3 4 5 6 7 1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
However, my pyramide needs to look like this: 但是,我的金字塔必须看起来像这样:
1 1
2 3 4 2 3 4
3 4 5 6 7 3 4 5 6 7
4 5 6 7 8 9 0 4 5 6 7 8 9 0
5 6 7 8 9 0 1 2 3 5 6 7 8 9 0 1 2 3
Thank you for your help and suggestions! 感谢您的帮助和建议!
just change the value of k
in your second loop like below (start with i
and border 3*i-2
): 只需在第二个循环中更改k
的值,如下所示(以i
和border 3*i-2
开头):
for (int i = 1; i <= n; i++ )
{
for (int j = 1; j < n; j++ )
System.out.print(" ");
n--;
for (int k = i; k <=3*i-2; k++ )
System.out.print(k%10);
System.out.println("");
}
OUTPUT: OUTPUT:
1
234
34567
4567890
567890123
67890123456
7890123456789
890123456789012
.................
The Simple Solution: use a counter outside of the loop and ignore the inside process. 简单解决方案:在循环外部使用计数器,而忽略内部进程。 Add one to it on each call and take that value modulo 10. 每次通话时加一个,取该值模10。
public static void trikotnik(int n) {
int val = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < n; j++)
System.out.print(" ");
n--;
for (int k = 1; k <= 2 * i - 1; k++)
System.out.print(val++%10);
System.out.println("");
}
}
Output: 输出:
1
234
56789
0123456
789012345
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.