What the heck is wrong with my code?
Hi everyone,
I've been working on this for days. My "program" is supposed to take an integer or double arrayList of numbers, and then calculate the standard deviation of those numbers using a generic method.
My code is listed below. I've tried fiddling with this for hours, but some error always pops up.
If anyone sees anything wrong, could you please show me the error(s) of my way?
Thanks!
Code Java:
import java.util.ArrayList;
class MyMathClass <T extends Number>
{
private ArrayList<T> myArrayList = new ArrayList<T>(10);
private ArrayList<T> myList = new ArrayList<T>(10);
public MyMathClass(ArrayList<T> al)
{
myArrayList = al;
myList = al;
}
public double standardDeviation(ArrayList<T> list)
{
double n = 0;
double avg = 0.0;
double s = 0.0;
double total = 0.0;
double answer = 0.0;
myList = list;
for (double i : myList) {
n++;
double d = i - avg;
avg = avg + d / n;
s = s + d * (i - avg);
System.out.println(s);
}
total = (s / n);
answer = Math.sqrt(total);
return answer;
}
}
Code Java:
class MyMathClassTest
{
public static void main(String args[])
{
System.out.println("Calculating Standard Deviation...\n");
double resultDouble = 0.0;
double resultInteger = 0.0;
ArrayList<Double> doubleArray = new ArrayList<Double>(10);
ArrayList<Integer> integerArray = new ArrayList<Integer>(10);
for (double i = 1.0; i <= 10.0; i++) {
doubleArray.add(i);
}
for (int i = 11; i <= 20; i++) {
integerArray.add(i);
}
MyMathClass<Double> myDouble = new MyMathClass<Double>(doubleArray);
MyMathClass<Integer> myInteger = new MyMathClass<Integer>(integerArray);
resultDouble = myDouble.standardDeviation(doubleArray);
System.out.println("\nanswer for double = " + resultDouble);
resultInteger = myInteger.standardDeviation(integerArray);
System.out.println("\nanswer for integer = " + resultInteger);
}
}
Re: What the heck is wrong with my code?
Quote:
but some error always pops up.
What error? Compile time? Run time? Posting them fully will facilitate you getting help.
Re: What the heck is wrong with my code?
Sorry, here is the compile error:
Code :
MyMathClass.java:29: incompatible types
found : T
required: double
for (double i : myList) {
^
1 error
Thanks!
Re: What the heck is wrong with my code?
The variable myList is specified by a generic - the compile time check prevents you from assuming it is a double (in other words doesn't allow you to iterate over the list that way). You know its a Number (eg T extends Number), so use the methods the class Number provides to retrieve the double value.