“不能取消引用double” [Java lang.]

这个问题已经在这里有了答案:            >            int cannot be dereferenced                                    3个
我不断收到错误:

“double can not be dereferenced” in the boolean line (line 45)

我从未见过此错误. inputdata.txt是一个文本文件,包含8个Item类输入.我想知道我的代码出了什么问题以及应该如何解决.

import java.util.Scanner;
import java.io.*;
public class Item implements Comparable
{

    public String item, category;
    public int quantity; 
    public double price;

    public Item(String itemName, String category, int quantity, double price)
    {
       this.item = item;
       this.category = category;
       this.quantity = quantity;
       this.price = price;
    }

    private Item[] list = new Item[8];
    private int n=0;

    public Item input() throws IOException
    {
        Item oneItem;
        Scanner scan = new Scanner ( new File ("Inputdata.txt"));
        while (scan.hasNext())
        {
           oneItem = new Item(scan.next(), scan.next(), scan.nextInt(), scan.nextDouble() );
           list[n] = oneItem;
           n++;
        }
    }

     public String toString()
    {
        String s = "";
        s += "[Clothing Name:" + item + ", Category: " + quantity + ", Price: " + price;
        return s;
    }

    public String getCategory()
    {
        return category;
    }

    public boolean equals (Object other)
    {
        return(price.equals(((Item)other).getPrice()) &&
        category.equals(((Item)other).getCategory()));
    }

     public int compareTo (Object other)
    {
        int result;

        double otherPrice = ((Item)other).getPrice();
        String otherCategory = ((Item)other).getCategory();

        if (price == otherPrice)
            result = price.compareTo(otherPrice);
        else if (price <otherPrice)
            result = -1;
        else 
            result = 1;

        return result;
    }

}

解决方法:

Java不允许在原语上调用方法.在这种情况下,它是equals()方法主体中的price.equals(…)调用.价格是原始的,因为它是两倍,并且是“dereference” basically means the method call.

使用==或a lenient comparison method.

上一篇:java 字符串大小比较


下一篇:Comparable和Comparator的区别