[英]Can't seem to get .doubleValue() to work (I have the latest version of Java)
So I am having problem with a method I created, called averageCost(). 所以我对我创建的方法有问题,称为averageCost()。 The error I get is:
我得到的错误是:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method doubleValue() is undefined for the type Double
at queue.averageCost(queue.java:38)
at queue.main(queue.java:47)
And previously I tried just adding a double value to a Double object which obviously didn't work. 之前我尝试过向Double对象添加一个double值,这显然不起作用。 So I found the .doubleValue method but I can't get it to work.
所以我找到了.doubleValue方法,但我无法让它工作。 I added all my code (everything else works just fine) in case that clears anything up.
我添加了所有代码(其他一切工作正常)以防万一。 I have been stuck on this for a couple days now while working on other stuff please help ):
我已经坚持了几天,现在在做其他事情时请帮忙):
import java.util.LinkedList;
public class queue<Double> {
private LinkedList<Double> linklist;
private String symbol;
private String name;
private int shares;
private Double price;
public queue(String symbol2, String name2, int shares2, Double price2) { //so far, I have a linkedlist that works
linklist = new LinkedList<Double>();
shares = shares2;
price = price2;
symbol = symbol2;
name = name2;
bigAdd(shares, price);
}
public void add(Double e) {
linklist.add(e);
}
public Double take() {
return linklist.poll();
}
public void bigAdd (int shares2, Double price2) {
while(shares2>0) {
linklist.add(price2);
shares2--;
}
}
public double averageCost(int shares2) {
double average = 0;
int sizer = 0;
while(sizer < shares2) {
average = average + linklist.poll().doubleValue(); //this is where the problem lies
sizer++;
}
average = average/shares2;
return average;
}
}
Your mistake comes from the class declaration. 你的错误来自课堂宣言。
Formal parameter of generic may be T: 泛型的形式参数可以是T:
public class queue<T> {
Now you see that T has no method named doubleValue because you haven't constrained it. 现在你看到T没有名为doubleValue的方法,因为你没有约束它。
The following do what you want: 以下做你想做的事:
import java.util.LinkedList;
public class queue<T extends Number> {
private final LinkedList<T> linklist;
private final int shares;
private final T price;
public queue( int shares2, T price2 ) {
linklist = new LinkedList<>();
shares = shares2;
price = price2;
bigAdd( shares, price );
}
public void add( T e ) {
linklist.add(e);
}
public T take() {
return linklist.poll();
}
public void bigAdd( int shares2, T price2 ) {
while(shares2>0) {
linklist.add(price2);
shares2--;
}
}
public double averageCost( int shares2 ) {
double average = 0;
int sizer = 0;
while( sizer < shares2 ) {
final T v = linklist.poll();
average = average + v.doubleValue();
sizer++;
}
average = average/shares2;
return average;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.