2013-10-11 5 views
-1

이 equals 메서드를 올바르게 작성하고 있는지 궁금합니다. 내 프로그램은 두 개의 객체 ItemotherObject이 같지 않아도 "동등"한 출력을 유지합니다. 나는 3 개의 equals 메소드를 가지고 있으며, 한 번에 하나씩 실행할 때 올바르게 작동하는 것 같지 않습니다. 3 개의 equals 메소드는 서로 참조 직후에 있습니다. 나의 주된 것이 끝이다. 당신이 Object#equals(Object)을 무시 찾고 있다면equal equals methods java hw

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 
+1

질문에 중요한 코드 만 사용하십시오. –

답변

2

, 당신의 방법 서명 그렇지 않으면 메소드를 오버로딩

public boolean equals(Object [some identifer]) 

을 할 필요가있다.

간단한 트릭은 @Override으로 재정의하려는 메소드에 주석을 달기위한 것입니다. 괜찮은 IDE라면 그 방법이 아무 것도 무시하지 않는다면 알려줄 것입니다.


그렇지 않으면, 당신이 anItem.name의에 otherObjectname을 설정 한 때문에

this.name.equals(otherObject.name) 

false를 반환합니다 아닌 것 같아.

+0

두 항목 모두에서'setName (null)'을 호출하고 동일성을 테스트 할 때 어떤 일이 일어나는지 테스트하는 것도 가치있을 것입니다. –

+1

@mike 오, 안돼! OP, 'null'참조를 확인하십시오. –

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

이 인쇄물은 equal입니다.

if 문을 너무 일찍 종료하면 다음 문이 항상 실행됩니다! name 필드이 비공개

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

단순하기 때문에 :

당신은 내가 당신의 equals 메소드가 있어야한다고 생각하여 if

if (anItem.equals(otherObject)) 
{System.out.println("\nequal");} 
0

;을 제거해야합니다.