因此,我对自己创建的称为averageCost()的方法有疑问。我得到的错误是:
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)
以前,我尝试仅向Double对象添加一个double值,这显然不起作用。因此,我找到了.doubleValue方法,但无法正常工作。我添加了所有代码(其他所有东西都很好),以防万一。我在处理其他内容时已经坚持了两天,请提供帮助:)
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;
}
}
最佳答案
您的错误来自类声明。
泛型的形式参数可以是T:
public class queue<T> {
现在您看到T没有名为doubleValue的方法,因为您没有对其进行约束。
以下是您想要做的:
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;
}
}
关于java - 似乎无法使.doubleValue()正常工作(我拥有最新版本的Java),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30923494/