2014-10-22 58 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否则

相关问题