【问题标题】:"double can not be dereferenced" [Java lang.] [duplicate]“无法取消引用双精度” [Java 语言。] [重复]
【发布时间】:2015-04-25 14:46:22
【问题描述】:

我不断收到错误:

布尔行中的“double can not be dereferenced”(第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 arrays compareto


    【解决方案1】:

    Java 不允许在原语上调用方法。在这种情况下,它是equals() 方法主体中的price.equals(...) 调用。 price 是原始的,因为它是 double"dereference" basically means the method call.

    使用==a lenient comparison method.

    【讨论】:

    • 感谢您的及时回复
    【解决方案2】:

    primitives 没有这样的方法equals()。使用== 进行比较。

    这里的价格是double,即primitive

    【讨论】:

      【解决方案3】:

      您将变量 price 声明为 double(原始)

      public double price;
      

      所以你不能在上面调用任何方法:

      price.equals(((Item)other).getPrice()
      

      【讨论】:

        猜你喜欢
        • 2016-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多