对于循环执行,增加混淆 [英] For loop execution, increment confusion
问题描述
我不明白为什么 i
in fillArray
方法最终等于 10
即使数组分数仅满足索引9
。
I don't get it why i
in fillArray
method ends up being equal to 10
even though the array score is filled only up to index 9
.
根据我的理解 i
必须小于 10
,那么它最终如何最终 10
,它应该增加。
As per my understanding i
has to be smaller than 10
,so how can it end up being 10
at the end, it should have incremented.
我尝试了另一个循环来测试for循环如果条件为真,for循环执行增量。
I tried another loop to test if for loop executes incrementation at the end if condition is true.
In测试循环 i
最终只有10才有意义,但两个for循环相矛盾。
In test loop i
ends up being only 10 which makes sense but the two for loop contradict.
public class GoldScores {
public static final int MAX_NUMBER_SCORES = 10;
public static void main(String[] args) {
double[] score = new double[MAX_NUMBER_SCORES];
int numberUsed = 0;
System.out.println("This program reads gold scores and shows");
System.out.println("how much each differs from the average.");
System.out.println("Enter gold scores:");
//numberUsed = fillArray(score);
// showdifference(score,numberUsed);
for(int i=1; i<11; i++){ //Test loop
System.out.println("Count is: " + i);
}
}
private static void showdifference(double[] score, int numberUsed) {
// TODO Auto-generated method stub
}
public static int fillArray(double[] a){
System.out.println("Enter up to " + a.length + " nonnegative numbers.");
System.out.println("Mark the end of the list with a negative number.");
Scanner keyboard = new Scanner(System.in);
double next = keyboard.nextDouble();
int i = 0;
for(i = 0;(next>=0 && i<a.length);i++){ //HELP!!!!
a[i] = next;
next = keyboard.nextDouble();
}
return i;
}
推荐答案
你必须完全明白 for
循环用于了解发生了什么,以及为什么 i
10
之后
循环
fillArray
。
You must understand exactly how the for
loop works to understand what is going on, and why i
is 10
after the for
loop in fillArray
.
- 在第一个分号之前执行初始化。
- 在第一个和第二个分号之间测试条件。如果条件是
false
,则跳出循环。 - 执行循环体。
- 在第二个分号(增量)后执行语句。
- 返回步骤2.
- Perform initialization, before the first semicolon.
- Test the condition in between the first and second semicolons. If the condition is
false
, break out of the loop. - Execute the body of the loop.
- Perform the statement after the second semicolon (the increment).
- Go back to Step 2.
在 i
for
循环的最后一次迭代中, i
是 9
,并且在数组中分配了索引 9
,步骤3.步骤4执行增量, i
现在 10
。然后然后测试条件,即 false
,并退出循环。 我
现在 10
。
In the last iteration of the i
for
loop, i
is 9
, and index 9
is assigned in the array, step 3. Step 4 performs the increment, and i
is now 10
. Then the condition is tested, which is false
, and the loop is exited. i
is now 10
.
但是,在你的对于循环, main
,您可以在正文中打印值,而不是之后检查循环变量。最后一次迭代是
i
是 10
,因为条件不同: i< 11
。如果你在之后打印
循环,你会看到它是 i
11
。
However, in your main
for
loop, you print the value in the body instead of examining the looping variable afterwards. The last iteration is when i
is 10
, because the condition is different: i < 11
. If you were to print i
after that for
loop, you'll see it's 11
.
这篇关于对于循环执行,增加混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!