2014-10-22 55 views
-2

因此,我在主要方法中輸入了一個大小爲8的數組,並調用此方法返回最高值分數,但是它只返回0.0。MEthod在輸入數組時沒有返回正確的結果

public static double Larger(double[] scoresRecived) 
    { 
     scoresRecived = new double[8]; 
     int c; 
     double largestScore = 0; 
     for (c = 0; c < 8; c++) 
     { 
      if (scoresRecived[c] > largestScore) 
       largestScore = scoresRecived[c]; 
     } 
     return largestScore; 
    } 
+0

,我認爲你應該返回'largestScore' – NewUser 2014-10-22 06:28:02

+0

@Andrew法伊答案張貼着輸出 – 2014-10-22 06:32:25

回答

0

您正在覆蓋本地的scoresRecived參數。只要刪除scoresRecived = new double[8];行。您可能想要返回largestScore

public static double Larger(double[] scoresRecived) 
{ 
    int c; 
    double largestScore = 0.0; 
    if (scoresRecived != null) { 
     for (c = 0; c < scoredRecived.length; c++) 
     { 
      if (scoresRecived[c] > largestScore) 
       largestScore = scoresRecived[c]; 
     } 
    } 
    return largestScore; 
} 
+0

我該如何解決它? – 2014-10-22 06:29:34

+0

@AndrewFey見編輯 – Eran 2014-10-22 06:32:27

0

您已重新聲明獲得它們後收到的分數。通過這樣做,你基本上忽略了函數中的參數輸入(因此你有一個空白數組)。

刪除此行,它應該工作

scoresRecived =新雙[8];

您也沒有返回正確的值。更改下面的行...

return largestScore;

也不是必需的,但可能想用它來代替不同的數組大小。

爲(C = 0; C^< scoresReceived.length; C++){

1
public static double Larger(double[] scoresRecived) 
{ 
    double largestScore = 0; 
    for (int i = 0; i < 8; i++) 
    { 
     if (scoresRecived[i] > largestScore) 
      largestScore = scoresRecived[i]; 
    } 
    return largestScore; 
} 
0
public class Test { 

    public static void main(String[] args) { 
     double[] d = { 2.0, 4.1, 1.5, 3.5, 4.3, 5.4, 6.4, 7.3 }; 
     System.out.println(Larger(d)); 
    } 

    public static double Larger(double[] scoresRecived) { 
     int c; 
     double largestScore = 0; 
     for (c = 0 ; c < 8 ; c++) { 
      if (scoresRecived[c] > largestScore) 
       largestScore = scoresRecived[c]; 
     } 
     return largestScore; 
    } 

} 

輸出

7.3 
0

你不需要重新初始化實際參數scoresRecived

目前您正在重新初始化它:

scoresRecived = new double [8];

通過這樣做,數組中的所有數據都將丟失。從代碼中刪除此行。

也在你的循環:

for (c = 0; c < scoresRecived.length; c++) 

與數組的大小更換c<8,U將得到arrayIndexOutOfBoundException否則

相關問題