2015-04-06 59 views
2

使用Java的第一天,當我將數組索引添加到變量minIndex時,出現for循環中的錯誤。 ()中的值我不確定要輸入什麼內容。我嘗試了我,但那不起作用,並且由於我在java中缺乏知識,我不確定。請給我一些指導。將數組索引號分配給for循環中的變量java

public static int minPosition(double[] list) { 
    double leastNum; 
    leastNum = list[0]; 
    // leastNum starts at first number in array 
    int minIndex; 
    minIndex = 1; 
    // minIndex starts at 1 as if first number in Array happens to be the lowest, its index will be one 
    for (int i = 0; i < list.length; i++) 
     if (list[i] < leastNum) 
      leastNum = list[i]; 
      minIndex = list.indexof(i); 
    return minIndex; 
+0

您需要語句塊大括號中的if語句 – scottb 2015-04-06 04:05:14

回答

1

i是索引。

變化

minIndex = list.indexof(i); 

minIndex = i; 

你也應該改變

minIndex = 1; 

minIndex = 0; 

,因爲陣列的第一個索引爲0.

正如已評論的那樣,您有一些缺失的大括號。下面是完整的代碼:

public static int minPosition(double[] list) { 
    double leastNum = list[0]; 
    // leastNum starts at first number in array 
    int minIndex = 0; 
    // minIndex starts at 0 as if first number in Array happens to be the lowest, its index will be one 
    for (int i = 0; i < list.length; i++) // you can also start with i = 1 
              // since you initialize leastNum 
              // with the first element 
     if (list[i] < leastNum) { 
      leastNum = list[i]; 
      minIndex = i; 
     } 
    return minIndex; 
} 
+0

他也需要周圍的if語句塊。 (在for語句中添加一個也是很好的樣式) – Lalaland 2015-04-06 04:03:41

+0

minIndex邏輯看起來不錯。它是數組中最小值的初始索引。無需將其與自身進行比較。 – scottb 2015-04-06 04:04:24

+0

謝謝@Eran這裏是我所做的,但目前我仍然有一個錯誤的錯誤狀態「我不能解決一個可變的」你能解釋請 – 2015-04-06 04:04:27

0

有一個在基本數組indexof()沒有這樣的方法:

public static int minPosition(double[] list) { 
    int minIndex = 0;//replaced 
    double leastNum = list[minIndex];//replaced 
    for (int i = 1; i < list.length; i++) {//braces recommended, also `i` starts with `1` 
     if (list[i] < leastNum) {//braces required, since you have more than one line to execute 
      leastNum = list[i]; 
      minIndex = i;//replaced 
     } 
    } 
    return minIndex; 
} 
+0

好吧,這使得很多的意義。現在我完全理解了大括號。謝謝 – 2015-04-06 04:40:13