gpt4 book ai didi

Java equals 方法的行为不符合预期

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:37 26 4
gpt4 key购买 nike

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;

}

}

以上是我调用的 equals 方法。他们显示错误的答案:在第一个实例中应该显示“它们不相等”,在第二个实例中将所有内容设置为彼此相等后,它应该显示“它们相等”。我已经非常努力地解决这个问题,但很多事情都没有成功。没有明显的错误,它运行良好,但我做错了一些事情,一些精确的指导将会有很大的帮助。许多模糊的暗示对我毫无帮助。我需要一些具体的东西,如果这对你有用的话。再次感谢您的帮助。以下是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());
}
}

最佳答案

我看到的原因很简单,您没有获得相同的名称

在 equals 中,您正在比较 super.getName()otherRestaurant.getName()

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

这是一个例子:

餐厅:

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

super 类:

public String getName(){
return name;
}

将导致将“A餐厅:KFC”“KFV”进行比较。

使用相同的 getter 可确保返回相同的“格式”。

<小时/>

Aslo,你的逻辑是错误的。您想要检查其中一个值是否不同,如果不同,返回 false。如果到达方法的末尾,意味着没有任何差异导致返回 false,则返回 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){}

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

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

关于Java equals 方法的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com