无法将双精度数组转换为数组

时间:2015-02-11 20:23:23

标签: java arrays double

我正在为我的高中计算机科学课做作业,我遇到了一个问题,我得到错误“double []无法转换为double”。但是,我很困惑,因为我告诉一个特定的方法来返回一个双数组。

public static double [] getHits(int attempts) {
    Random ranInt = new Random();
    int range = ranInt.nextInt(2) - 1;

    double hits = 0;
    double [] hitsInTrial = new double[attempts];
    double radius = 1;
    double x = Math.pow( range, 2);
    double y = Math.pow( range, 2);

    for( int index = 0; index < attempts; index++)
    {
        if( !(x + y <= radius) )
        {
            hits++;
        }

        hitsInTrial[index] = hits;
    }

    return hitsInTrial;
}

^这个方法应该返回hitsInTrial的双数组(我感觉好像有些数据是错误的,但是在我解决了问题之后我会担心这个)。

public static void main()
{
    Scanner in = new Scanner(System.in);

    System.out.print("How many darts/trials?: ");
    int dartThrows = in.nextInt();

    double[] trials = new double[10];
    double[] hits = new double[dartThrows];

    for( int index = 0; index < trials.length; index++)
    {
        hits[index] = getHits( dartThrows );
    }
}

我在点击[index] = getsHits(dartThrows)中收到错误;区域。我很困惑,因为方法getHits被告知返回一个双精度数组,但我得到“无法转换”错误。任何帮助将不胜感激,因为作为一个新手,我不太确定是什么问题。

我遗漏了两种方法,一种是使用数据计算pi,另一种是打印结果。这些方法不会产生任何错误,但如果我需要提供它们以帮助解答,请告诉我。

2 个答案:

答案 0 :(得分:6)

您的getHits()方法返回一系列双精度数:double[]。您的hits[]数组的类型为double[],因此其元素的类型为double。您尝试为其分配double[]返回值。

答案 1 :(得分:1)

执行hits = getHits( dartThrows );

您正在尝试将双精度数组分配给数组中的double元素。

hits[a] // Represents a double element at index a not the array itself