簡體   English   中英

Java等於方法不符合預期

[英]Java equals method not behaving as expected

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());
    }
}

我看到的原因很簡單,你沒有得到同一個name

在equals中,您將super.getName()otherRestaurant.getName()進行比較

如果Restaurant的超類具有不同的格式或返回其他變量,因為您將它與Restaurant.getName()進行比較,這將比較不同的值。 使用this.getName()來比較相同的變量(或變量的格式)更安全。 即使Restaurant.getName()僅返回super.getName() ,如果您更改了Restaurant的方法(因為您更喜歡它的另一種方式),這將更安全。

這是一個例子:

餐廳:

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以防止像這樣的問題,如果你在方法中指定類型,它將不會正確覆蓋該方法(取決於類型)

看起來你正在檢查是否相等然后返回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()的任何理由?

並且由於peopleServed&averagePrice不能為null,因此不需要-1檢查,因為預期結果我們與相等檢查相同

最后,我猜測結束返回應該是真的,因為它意味着它是一個對象的不同實例,但它們具有相同的屬性。

在你的equals()方法中,如果super.name()等於otherRestaurant.name()你不應該返回true ,這里:

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

好吧,那個在任何情況下都可以工作:

@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;
    }

檢查並回答它是否正常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM