Shahrokh Aryana - 10 months ago 34

Java Question

im trying to calculate the variance of a the set of data inputted by a user. However, when i run my program, im getting the error: method variance in class Test cannot be applied to given types.

This is my code so far:

`public static double variance(ArrayList<Double> numbers, double mean) {`

double variance = 0;

for (int i = 0; i <numbers.size(); i++) {

variance = variance + Math.pow((numbers.get(i) - mean(numbers)), 2);

}

return variance/numbers.size();

}

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter data set: ");

ArrayList<Double> nums = new ArrayList<Double>();

while (keyboard.hasNextDouble()) {

nums.add(keyboard.nextDouble());

}

double numbs = mean(nums);

System.out.println("Mean = " + numbs);

double numbs2 = variance(nums);

System.out.println("Variance = " + numbs2);

}

}

I have a method above the Variance method which calculates the mean of the ArrayList, would that be useful in anyways, despite me initialising a double mean in the variance method?

Answer

Adjust your

`variance`

method to accept one argument, like so`public static double variance(ArrayList<Double> numbers) { double variance = 0; for (int i = 0; i <numbers.size(); i++) { variance = variance + Math.pow((numbers.get(i) - mean(numbers)), 2); } return variance/numbers.size(); }`

Define the method

`mean`

similar to this, and the rest should be fine.`public static double mean(ArrayList<Double> numbers) { double sum = 0; for (int i = 0; i < numbers.size(); i++) { sum += numbers.get(i); } return sum / numbers.size(); }`