3 回答

TA貢獻1869條經(jīng)驗 獲得超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條經(jīng)驗 獲得超1個贊
你應(yīng)該使用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));
}
}
}
但是,這將打印整個數(shù)組,因為它正在被填充:
[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條經(jīng)驗 獲得超3個贊
您需要兩個循環(huán),一個循環(huán)用于行,然后另一個循環(huán)用于每行的數(shù)字。
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");
}
當(dāng)然,您可能需要根據(jù)您的喜好進一步格式化輸出。
添加回答
舉報