user1730056
user1730056

Reputation: 623

Java arrays in methods

I'm making a method that take a list of arrays and finds the average of the numbers. I know that my method works since I just moved it from my main method to the "average" method. I'm just having problems getting the array to work with the method.

I'm not sure if I'm wrong by calling the method by average(a);, or if it's because the method is written as public static void average(double[] a){

Could someone point me to the right direction?

public class Ass10{

    public static void main(String[] args) {
        System.out.println("asdf");
        int a[] = {1, 2, 3,4};
        average(a);
      }

    public static void average(double[] a){
        int sum = 0;

        for (int counter = 0; counter<a.length;counter++){
            sum += a[counter];
        }
                System.out.println(sum/a.length)

        }

Upvotes: 3

Views: 144

Answers (2)

Jatin
Jatin

Reputation: 31754

int and double in Java are primitives and not Objects. Further their arrays are not covariant. (Co-variance of array mean if A extends B, then A[] extends B[])

Hence you cannot use double[] where int[] is required. This should do public static void average(int[] a){

Secondly, sum += a[counter]; will cause loss of precision as sum is type int and a is of type double

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

You can try changing public static void average(double[] a) to public static void average(int[] a)

Upvotes: 1

Related Questions