1

I am currently doing an assignment for my high school computer science class and I am running into an issue where I get the error "double[] cannot be converted to double". However, I'm very confused because I'm telling one specific method to return a double array.

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;
}

^This method is supposed to return the double array of hitsInTrial (I feel as if some data is wrong but I'll worry about that after I get my issue resolved).

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 );
    }
}

I am getting the error in the hit[index] = getsHits( dartThrows ); area. I'm very confused because the method getHits is told to return an array of doubles, but I'm getting the "Cannot be converted" error. Any help would be greatly appreciated because as a newbie, I'm not quite sure what's wrong.

I have left out two methods, one to calculate pi using the data, and one to print the results. No errors are generated in those methods but if I need to provide them to help with an answer please let me know.

2 Answers 2

6

Your getHits() method returns an array of doubles: double[]. Whereas your hits[] array is of type double[], so its element is of type double. You try to assign a double[] return value to it.

Sign up to request clarification or add additional context in comments.

Comments

1

Do hits = getHits( dartThrows );

You are trying to assign the array of doubles to a double element in the array.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.