形成等于方法java hw

时间:2013-10-11 17:28:41

标签: java equals

我想知道我是否正确地编写了这个equals方法。我的程序不断打印出来"相等"即使两个对象ItemotherObject不相等。我有三个equals方法,一次运行一个似乎没有工作。三个等于方法正好位于彼此之后以供参考。我的主要是在最后。

 import static java.lang.System.*;

 import java.text.DecimalFormat;
 import java.util.Arrays;
 import java.util.Scanner;
 import java.math.*;
public class Item {
     DecimalFormat df = new DecimalFormat("#.00"); 

    //the properties of an Item
    static double cash=59.00;
    static double sum=0.00;
    private    int priority;
    private String name;
    private double price;
    static boolean value= false;

    //default constructer
    public Item() {
        priority = -1;   //fill with default values
        price = 0.00;
        name = "No name yet";
    }

    public Item(int priority, String name, double price) {//constructor with all 3     arguments 
        this.priority = priority; 
        this.name = name;         
        this.price = price;
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        //priority must be between 1 and 7
        if (priority > 0 && priority <= 7) {

            this.priority = priority;
        } else {

            System.err.println("Error, enter 1 through 7"); 

        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {


        this.name = name;
    }

    public double getPrice() {
        return price;

    }

    public void setPrice(double price) {

        //price between 0 and 100 inclusive
        if (price >= 0.00) {
            if (price <= 100.00) {
                this.price = price;
                cash = cash-=price;
                sum=sum+=price;

            } else {

                System.err.println("Error: price to high");
            }
        } else {
            System.err.println("Error: price to low");
        }
    }

        public boolean equals(Item otherObject) {
        return this.name.equals(otherObject.name);



    }

        /*public boolean equals(Item otherObject) {
            if(this.getPriority()==(otherObject.getPriority()));

                return true;
        }  */        

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + priority;
        return result;
    }


    /*@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Item))
            return false;
        Item other = (Item) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (priority != other.priority)
            return false;
        return true;
    }*/

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Item [Price= ").append(getPrice()).append(", ");
        if (getName() != null) {
            builder.append("Name= ").append(getName()).append(", ");
        }
        builder.append("Priority= ").append(getPriority()).append("]");
        return builder.toString();
    }

    public static void main (String[] args) {

        Item[] list = new Item[2];
        Scanner keyboard = new Scanner(System.in);


        for (int i = 1; i <= list.length; i++) {

            if(cash==59)
            {
                System.out.println("You have 59 dollars");
            }

            Item otherObject=new Item();
            Item anItem = new Item(); // new item object created 7 times

            System.out.println("Enter an item you want to add to your list " + i);
            anItem.setName(keyboard.next());

            System.out.println("Enter a price " + i);
            anItem.setPrice(keyboard.nextDouble());

            System.out.println("Enter the priority of the item " + i);
            anItem.setPriority(keyboard.nextInt());

            list[i-1] = anItem;

            System.out.println("Cash left "+cash);
            System.out.println("Sum of Items "+sum); 
            System.out.println(Arrays.toString(list));

            if (anItem.equals(otherObject)); //--------------- This is printing out each time. Is it comparing default constructors? 
             {System.out.println("\nequal");}

     }
      if(sum>59)
         {System.err.println("Error, you ran out of money\t\t");

        }
   // int a;
    //int b;
    //a=list[0].getPriority();
   // b=list[1].getPriority();
    //System.out.println(a +" here");
   // System.out.println(b +" here");

    //final int[] arraySort = { a, b,}; 
    Item temp;

    for (int i = 0; i < list.length; i++) {

        //min = i;
        for (int j = 1; j < (list.length - i); j++)  {
            if (list[j-1].getPriority() > list[j].getPriority()) {
                temp = list[j - 1];
                list[j - 1] = list[j];
                list[j] = temp;

            }
        }   //min = j;
        System.out.println(list[i]);
    }

    } //main    
   }// class Item

3 个答案:

答案 0 :(得分:5)

if("foo".equals("bar"));
{System.out.println("\nequal");}

这也会打印equal

您过早结束if语句,因此始终会执行下一个语句!

您需要在;

之后删除if
if (anItem.equals(otherObject))
{System.out.println("\nequal");}

答案 1 :(得分:2)

如果您要覆盖Object#equals(Object),则您的方法签名必须是

public boolean equals(Object [some identifer])

否则你正在重载该方法。

简单的技巧是注释要用@Override覆盖的方法。任何体面的IDE都会告诉你该方法是否没有覆盖任何内容。


否则,您似乎不会将name的{​​{1}}设置为otherObject的{​​{1}},因此

anItem.name

将返回this.name.equals(otherObject.name)

答案 2 :(得分:0)

我认为你的平等方法应该是:

public boolean equals(Item otherObject) {
        return this.name.equals(otherObject.getName());   
    }

简单,因为name字段是私有的。