asit said:
//Stats.java
package tutorial;
public class Stats<T> {
T[] nums;
Stats(T x){
nums=x;
}
double average() {
double sum=0;
for(int i=0;i<nums.length;i++)
sum += nums.doubleValue();
return sum;
}
//Demo.java
package tutorial;
public class Demo {
public static void main(String[] args){
int[] x= {1,2,3,4,5,6,7,8,9,10};
Stats<Integer> ob = new Stats<Integer>(x);
System.out.println(ob.average());
}
}
How can we debug the program if we don't know what
it's supposed to do? That is, if somebody offered code
that printed "Bonjour, Welt!" would you be happy?
Still, we can at least point out some of the things
that cannot possibly be right, no matter what the code
is supposed to do:
- The assignment in the constructor for Stats will
not compile. The l.h.s. is an array reference,
and the r.h.s. is not. I imagine that the argument
should have been a T[] rather than a T.
- The use of `nums.doubleValue()' will not compile.
`nums' is an array, and an array has no method
named doubleValue().
- Even if you change to `nums
.doubleValue()' the
line still won't compile. You have not told Java
anything about the type T, so Java has no reason to
believe that a T object has a doubleValue() method.
- There's nothing ipso facto wrong about the value
returned by the average() method, except that you
seem to have chosen a misleading name ...
- In main(), x is of type int[]: a reference to an array
whose elements are `int' values. But the constructor
(if altered as suggested above) expects an Integer[]:
a reference to an array whose elements are references
to Integer objects. Not the same thing at all ...
Other remarks: It's unusual for a public class to have a
package-private constructor. Also, your life will be easier
if you use indentation to make your code's logical structure
more apparent. Ifyoudon'tthinkjudicioususeofwhitespaceandsi
milartricksofformattingareaidstocomprehension,it'sbecauseyou
don'tcomprehend.