Java等于方法不符合预期

时间:2017-02-06 08:51:36

标签: java

package restaurantclient;

public class Restaurant extends Store {

//Instance Variables
private int peopleServed; 
private double averagePrice; 

//Constructor with 3 parameters
public Restaurant(String storename, int peopleServed, double averagePrice) {
super(storename);
setPeopleServed(peopleServed);
setAveragePrice(averagePrice);
}

//Getters (Accessors)
public int getPeopleServed() { 
return peopleServed; 
} 

public double getAveragePrice() { 
return averagePrice; 
} 

//Setters (Mutators)
public void setPeopleServed(int peopleServed) { 
this.peopleServed = peopleServed; 
}

public void setAveragePrice(double averagePrice) { 
this.averagePrice = averagePrice; 
} 

//toString Method [Must Override]
@Override
public String toString() {
    String information = "Store name: " + (super.getName());
    information += "\n" + "The number of people served: " + peopleServed;
    information += "\n" + "The average price per person: $" + averagePrice;

    return information;
    }

//Equals Method
@Override
public boolean equals (Object other) {

    if (this == other)
        return true;
    if (other == null)
        return false;
    if (!(other instanceof Restaurant))
        return false;

   Restaurant otherRestaurant = (Restaurant) other;

    if (this.getName() == null) {
        if (otherRestaurant.getName() != null)
            return false;
    }   else if (!(this.getName().equals(otherRestaurant.getName())))
            return false;

    if (peopleServed == -1) {
        if (otherRestaurant.peopleServed != -1)
            return false;
    }   else if (peopleServed != (otherRestaurant.peopleServed))
            return false;

    if (averagePrice == -1) {
        if (otherRestaurant.averagePrice != -1)
            return false;
    }   
        else if (averagePrice != (otherRestaurant.averagePrice))
            return false;

    return true;
}


public double getAverageTaxes() { 
double total; 
total = this.getPeopleServed() * this.getAveragePrice() 
* super.CA_TAX_RATE; 
return total; 
} 
}


   package restaurantclient;


public class Store {

//Instance Variables
protected final double CA_TAX_RATE = 0.0884; 
private String storename; 

//Constructor
public Store(String storename) { 
    setName(storename); 
    } 

//Getters (Accessors)
public String getName() { 
    return storename; 
    } 

//Setters (Mutators)
public void setName(String storename) { 
    this.storename = storename; 
    } 

//toString Method [Must Override]
@Override
public String toString() {
    String directory = "Name of store: " + storename;

    return directory;
    }

//Equals Method
public boolean equals (Store storename) {

    if (this == storename)
        return true;
    if (storename == null)
        return false;
    if (!(storename instanceof Store))
        return false;

    return true;

    }

}

以上是我正在调用的等于方法。他们正在显示错误的答案:它应该在第一个实例中,“它们不相等”,在第二个实例中,在将所有内容设置为彼此相等之后,它应该显示“它们是相等的”。我已经非常努力地解决了这个问题,很多事情都没有奏效。没有明显的错误它运行正常,但我做错了,一些精确的指导会有很多帮助。大部分模糊的暗示让我无处可去。如果这对你有用,我需要一些具体的东西。再次感谢您的帮助。以下是Client类:

package restaurantclient;  

public class RestaurantClient { 
public static void main(String[] args) { 
    Restaurant r1 = new Restaurant("McDonald's", 1000000, 8.00);
    Restaurant r2 = new Restaurant("KFC", 500000, 6.00);

    System.out.println(r1.toString());
    System.out.println(r2.toString());
    System.out.println();

    r2.setAveragePrice(r1.getAveragePrice());
    r2.setPeopleServed(r1.getPeopleServed());

    System.out.println(r1.toString());
    System.out.println(r2.toString());

    if (r1.equals(r2))  {
        System.out.println("The objects are equal.");
        }
    else {
        System.out.println("The objects are not equal."); //SHOULD say "not equal" here EVERY TIME the second instance (next comment down) says "Equal"...this should never change. 
        System.out.println();
        }

    System.out.println();
    r2.setName(r1.getName());

    System.out.println(r1.toString());
    System.out.println(r2.toString());

    if (r1.equals(r2)) {
        System.out.println("The objects are equal."); //Now that everything is equal, it should print "The Objects are Equal" but it doesn't. It's in lock-step with the previous instance. Changing some things like return true to return false might make both these instances "Are equal" and some might change them to "Not Equal" but they are never the way I want them, which is when 2 changes are made, they are not equal (first case) and when the third and final change is made (like this case here on this line) it should say "the obj are equal" but it doesn't. 
    }
    else {
        System.out.println("The objects are not equal.");
        System.out.println();
    }    

    System.out.println();
    System.out.print("The avg. annual taxes paid by the restaurant is: $");
    System.out.println(r1.getAverageTaxes());
    }
}

4 个答案:

答案 0 :(得分:1)

我看到的原因很简单,你没有得到相同的name

在等号中,您将super.getName()otherRestaurant.getName()

进行比较

如果Restaurant的超类具有不同的格式或返回其他变量,因此您将其与Restaurant.getName()进行比较,这将比较不同的值。使用this.getName()来比较相同的变量(或变量的格式)更安全。 即使Restaurant.getName()仅返回super.getName(),如果您更改了餐厅的方法(因为您更喜欢其他方式),这会更安全。

以下是一个例子:

餐厅:

public String getName(){
    return "A restaurant " + name;
}

超级课程:

public String getName(){
    return name;
}

"A restaurant : KFC""KFV"进行比较。

使用相同的getter确保您返回相同的"格式"。

Aslo,你的逻辑错了。您想检查其中一个值是否不同,如果是,return false。如果你到达方法的末尾,意味着没有导致return false的差异,那么你就是return true

if (this.getName() == null) {
    if (otherRestaurant.getName() != null)
        return false;
}   else if (!super.getName().equals(otherRestaurant.getName())) // added ! here
        return false;

if (peopleServed == -1) {
    if (otherRestaurant.peopleServed != -1)
        return false;
}   else if (peopleServed != (otherRestaurant.peopleServed)) // change to != here
        return false;

if (averagePrice == -1) {
    if (otherRestaurant.averagePrice != -1)
        return false;
}   
    else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
        return false;

//No differences, then it is equals.
return true;

注意:

这种情况可能会缩短

if (averagePrice == -1) {
    if (otherRestaurant.averagePrice != -1)
        return false;
}   
    else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
        return false;

因为它做了同样的事情(比较值):

if (averagePrice != (otherRestaurant.averagePrice))
    return false;

编辑:

您遇到了覆盖问题。

在商店中:

public boolean equals(Store s){}

在餐厅

public boolean equals(Object o){}

由于您使用RestaurantStore的子类)调用方法,因此JVM将使用Store.equals方法,因为它与类型匹配,Restaurant.equals不是覆盖它,它会覆盖Object中的方法。更改为Store.equals(Object o)以更正此问题。

方法equals来自Object所以应始终接收Object以防止出现此问题,如果您在方法中指定类型,则不会覆盖正确的方法(取决于类型)

答案 1 :(得分:0)

似乎你正在检查是否存在相等性,然后返回false,当你应该检查不等于返回false时。

else if (!super.getName().equals(otherRestaurant.getName()))
            return false;

else if (peopleServed != (otherRestaurant.peopleServed))
            return false;

else if (averagePrice != (otherRestaurant.averagePrice))
            return false;

同样有问题,任何使用super.getName()的原因?

自从人们服务并且averagePrice不能为null,不需要-1检查,因为预期结果我们与等式检查相同

最后,我猜测结束返回应该是真的,因为它意味着它是对象的不同实例,但它们具有相同的属性。

答案 2 :(得分:0)

equals()方法中,如果super.name()等于otherRestaurant.name(),则不应返回true,此处:

  

else if(super.getName()。equals(otherRestaurant.getName()))返回false;

答案 3 :(得分:-1)

好的,在任何情况下都适用:

@Override
    public boolean equals (Object other) {

        if (this == other)
            return true;
        if (other == null)
            return false;
        if (!(other instanceof Restaurant))
            return false;

        Restaurant otherRestaurant = (Restaurant) other;

        if (name == null) {
            if (otherRestaurant.getName() != null)
                return false;
        }   else if (name!=otherRestaurant.getName())
            return false;

        if (peopleServed == -1) {
            if (otherRestaurant.peopleServed != -1)
                return false;
        }   else if (peopleServed != otherRestaurant.peopleServed)
            return false;

        if (averagePrice == -1) {
            if (otherRestaurant.averagePrice != -1)
                return false;
        }
        else if (averagePrice != otherRestaurant.averagePrice)
            return false;

        return true;
    }

检查并回复是否正常