3 回答
TA贡献1869条经验 获得超4个赞
您可以尝试流:
import java.util.stream.Collectors;
import java.util.stream.IntStream;
IntStream.range(0, 15).forEach(
x -> System.out.println(
IntStream.rangeClosed(0, x)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ")))
);
输出:
0
0, 1
0, 1, 2
0, 1, 2, 3
0, 1, 2, 3, 4
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6
0, 1, 2, 3, 4, 5, 6, 7
0, 1, 2, 3, 4, 5, 6, 7, 8
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
TA贡献1780条经验 获得超1个赞
你应该使用Arrays.toString,像这样:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] table = new int[11];
for ( int i = 0; i <=10; i++){
table[i] = i;
System.out.println(Arrays.toString(table));
}
}
}
但是,这将打印整个数组,因为它正在被填充:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果您只想填充到目前为止的元素,则需要更多的参与:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] table = new int[11];
for ( int i = 0; i <=10; i++){
table[i] = i;
for(int j = 0; j <= i; j++)
{
System.out.print((j == 0 ? "" : ", ") + table[j]);
}
System.out.println();
}
}
}
输出:
0
0, 1
0, 1, 2
0, 1, 2, 3
0, 1, 2, 3, 4
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6
0, 1, 2, 3, 4, 5, 6, 7
0, 1, 2, 3, 4, 5, 6, 7, 8
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
TA贡献1712条经验 获得超3个赞
您需要两个循环,一个循环用于行,然后另一个循环用于每行的数字。
for (int i=0; i<=10; i++) {
table[i] = i;
for (int j=0; j<=i; j++) {
System.out.print(table[j]);
}
System.out.print("\n");
}
当然,您可能需要根据您的喜好进一步格式化输出。
添加回答
举报