如何使用Java中的循环用整数填充数组 [英] How to fill an array with int numbers using a loop in Java
本文介绍了如何使用Java中的循环用整数填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新手,我要完成一个练习,即编写一个简单的程序,该程序将在控制台中生成一个数组:
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,
我在Google上搜索类似的问题失败,这将使我找到解决办法.
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);
}
}
推荐答案
您应使用 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));
}
}
}
但是,这将打印整个数组,因为它正在填充:
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();
}
}
}
输出:
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
这篇关于如何使用Java中的循环用整数填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文