[英]Java - Storing the output of a for loop into an array
I'm using a for loop to create the first 400 multiples of 13, and I'm trying to to store these numbers into an array. 我正在使用for循环来创建13的前400个倍数,我正在尝试将这些数字存储到数组中。 The specific issue is on 5th line.
具体问题在第5行。 I understand that this code is making the programme write to the first element of the array, which is causing the issue.
我知道这段代码正在使程序写入数组的第一个元素,这导致了问题。 Is there any way I can store the numbers sequentially?
有什么方法可以按顺序存储数字吗?
public static void main(String[] args) {
int[] thirteenMultiples = new int[400];
for (int dex = 1; dex < thirteenMultiples.length; dex ++) {
int multiples = 13 * dex;
thirteenMultiples[0] = multiples;
System.out.println(Arrays.toString(thirteenMultiples));
Array indices start at 0, so change int dex = 1
to int dex = 0
. 数组索引从0开始,因此将
int dex = 1
更改为int dex = 0
。 Also, you should use your counting variable dex
to write to the right array index: 此外,您应该使用计数变量
dex
写入正确的数组索引:
public static void main(String[] args) {
int[] thirteenMultiples = new int[400];
for (int dex = 0; dex < thirteenMultiples.length; dex ++) {
int multiples = 13 * dex;
thirteenMultiples[dex] = multiples;
System.out.println(Arrays.toString(thirteenMultiples));
}
}
BTW: Arrays.toString(thirteenMultiples)
is quite an expensive operation to do on every iteration (try to code this method yourself and you'll see what i mean). 顺便说一句:
Arrays.toString(thirteenMultiples)
在每次迭代时都是相当昂贵的操作(尝试自己编写这个方法,你会看到我的意思)。 Maybe you should just print the current value of thirteenMultiples[dex]
and print you array once the loop has finished. 也许你应该只打印
thirteenMultiples[dex]
的当前值,并在循环结束后打印出你的数组。 I assume you're just testing and trying stuff for now, but i think it's good to keep such things in mind from the beginning ;) 我认为你现在只是测试和尝试的东西,但我认为从一开始就记住这些事情是好的;)
thirteenMultiples[dex] in place of thirteenMultiple[0], because dex is equal to the index each time for loop runs. 13个多个[dex]代替13个多个[0],因为每次循环运行时dex等于索引。 For ex - for dex =1 you store multiple at [1], then it increases to 2 then it becomes [2] and you store the next multiple at 2. Hence it stores each new value at new index.
对于ex - 对于dex = 1,您在[1]处存储多个,然后它增加到2然后它变为[2]并且您将下一个倍数存储在2.因此它将每个新值存储在新索引处。
Also start dex from 0 as array starts from 0 index. 当数组从0索引开始时,也从0开始dex。
I guess in this case, it is better to use a List rather than an array. 我想在这种情况下,最好使用List而不是数组。 Your code will look cleaner
您的代码看起来更干净
public static void main(String[] args) {
List<Integer> thirteenMultiples = new ArrayList<Integer>;
for (int dex = 0; dex < 400; dex ++) {
thirteenMultiples.add(13 * dex)
}
System.out.println(thirteenMultiples);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.