[英]For loop execution, increment confusion
我不明白為什么即使數組分數僅填充到index 9
i
在fillArray
方法中最終還是等於10
。
根據我的理解, i
必須小於10
,那么最后它怎么可能變成10
,它應該增加了。
我嘗試了另一個循環來測試如果條件為true,則for循環是否在最后執行增量。
在測試循環中, i
最終只有10,這是有道理的,但是兩個for循環是矛盾的。
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
循環的工作原理以了解發生了什么,以及為什么fillArray
for
循環之后i
只有10
fillArray
。
false
,則跳出循環。 在i
for
循環的最后一次迭代中, i
為9
,並在數組中分配索引9
(第3步)。步驟4執行增量,而i
現在為10
。 然后測試條件,條件為false
,並退出循環。 i
現在10
。
但是,在您的main
for
循環中,您將在主體中打印該值,而不是隨后檢查循環變量。 最后一次迭代是當i
為10
,因為條件不同: i < 11
。 如果要在for
循環之后打印i
,您會看到它是11
。
在For循環中,增量發生在測試循環條件之后,而不是之前。 因此,在上一次迭代中,當檢查您的條件時,我已經等於10,而這恰恰是返回的結果。 考慮一下這一點,如果您在上一次迭代中仍為9,則您的條件仍然為true,這意味着需要循環執行一次。
盡管其他人已經詳細解釋了,但是為了消除混亂,您可以將代碼修改為:
double next = keyboard.nextDouble();
int i = 0;
int current_i = i;
for( i = 0; ( next >= 0 && i < a.length ); i++ )
{
current_i = i;
a[i] = next;
next = keyboard.nextDouble();
}
return current_i;
代替
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.