问题
I am a newbie and I am to fulfill an exercise which is to write a simple program which would produce an array in console:
0,
0, 1,
0, 1, 2,
I failed at google searching similar problems which would direct me at a solution.
I will greatly appreciate your help. This is what i have been trying to build upon, but I am completely stuck:
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(i);
}
}
回答1:
You should use Arrays.toString
, like so:
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));
}
}
}
However, this will print the entire array, as it is being populated:
[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]
If you just want the elements filled so far, it's a little more involved:
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();
}
}
}
Output:
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
回答2:
You can try streams:
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(", ")))
);
Output:
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
回答3:
You need two loops, one loop for the rows and then an additional loop for the numbers per row.
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");
}
Of course you might need to further format the output to your liking.
来源:https://stackoverflow.com/questions/58326653/how-to-fill-an-array-with-int-numbers-using-a-loop-in-java