2016-10-23 4 views
0

Integer, Double, Book 및 PlayingCard 객체가 포함 된 ArrayList < 개체를 정렬해야하는 클래스에 대한 지정이 있습니다. 우리는 정렬을 위해 'instanceof'키워드와 'compareTo'메소드를 사용해야합니다. 나는 "compare"라는 이름의 메서드에 문제가 있습니다. 목록에서 두 요소를 사용하고 어떤 형식인지를 확인한 다음 동일한 형식 인 경우에는 compareTo 메서드를 사용하여 정렬합니다. 정수와 Doubles는 동일한 유형의 두 객체 만 비교할 수 있기 때문에 함께 정렬되는 것과 동일한 유형으로 처리되어야합니다. compareTo 메소드에 문제가있는 것으로 알고 있습니다. 전달 된 두 요소 (a.compareTo (b))를 사용하여 compareTo 메서드를 호출 할 때마다 계속 '기호를 찾을 수 없습니다'오류가 발생합니다. 내가 그들을 각각의 클래스 유형으로 객체 유형에서 변환 시도 ... 아무 소용. 나는 내가 여기서 잘못하고있는 것이 확실하지 않다. 어떤 도움이라도 대단히 감사합니다. Book 또는 PlayingCard 클래스의 코드를 볼 필요가있을 때도 제공 할 수 있습니다. (그리고 예, Book과 PlayingCard는 각각 compareTo 메소드를 가지고 있고 둘 다 Comparable을 구현합니다). 여기 정렬 프로그램의 비교 방법에서 '심볼을 찾을 수 없습니다'오류가 발생했습니다.

코드입니다 :

import java.util.ArrayList; 

public class Sorter { 
    /** 
    * Checks two objects in the list to see what type they are, 
    * if they are the same type, use compareTo method to sort, 
    * otherwise, sort in order of Integer and Double > Book > PlayingCard. 
    * 
    * @param a first object 
    * @param b second object 
    * @return a negative number if a < b, a positive number if a > b, 
    *   0 if a = b 
    */ 
    public static int compare(Object a, Object b) { 
     if ((a instanceof Integer || a instanceof Double) && (b instanceof Integer || b instanceof Double)) { 
      return a.compareTo(b); 
     } 
     else if ((a instanceof Integer || a instanceof Double) && (b instanceof Integer == false || b instanceof Double == false)) { 
      return -1; 
     } 
     else if ((a instanceof Integer == false || a instanceof Double == false) && (b instanceof Integer || b instanceof Double)) { 
      return 1; 
     } 
     else if ((a instanceof Book) && (b instanceof PlayingCard)) { 
      return -1; 
     } 
     else if ((a instanceof PlayingCard) && (b instanceof Book)) { 
      return 1; 
     } 
     else if ((a instanceof Book) && (b instanceof Book)) { 
     return a.compareTo(b); 
     } 
     else { 
     return a.compareTo(b); 
     } 
    } 

/** 
* Sort a list of objects. Uses the selection sort algorithm. 
* 
* @param stuff list of objects 
*/ 
public static void sort(ArrayList<Object> stuff) { 
    // selection sort 
    for (int i = 0; i < stuff.size() - 1; i++) { 
     int lowest = i; 
     for (int j = 1; j < stuff.size(); j++) { 
      if (compare(stuff.get(j), stuff.get(lowest)) < 0) { 
       lowest = j; 
      } 
     } 

     // swap to front 
     if (lowest != i) { 
      Object temp = stuff.get(i); 
      stuff.set(i, stuff.get(lowest)); 
      stuff.set(lowest, temp); 
     } 
    } 
} 

/** 
* Main method. Populates an arraylist of stuff and sorts it. 
* 
* @param args command-line arguments 
*/ 
public static void main(String[] args) { 
    ArrayList<Object> list = new ArrayList<>(); 

    list.add(8); 
    list.add(new PlayingCard(PlayingCard.HEARTS, PlayingCard.TWO)); 
    list.add(3.5); 
    list.add(new Book("Mark Twain", "The Adventures of Huckleberry Finn")); 
    list.add(new Book("F. Scott Fitzgerald", "The Great Gatsby")); 
    list.add(5.65); 
    list.add(new PlayingCard(PlayingCard.CLUBS, PlayingCard.SEVEN)); 
    list.add(new PlayingCard(PlayingCard.SPADES, PlayingCard.ACE)); 

    System.out.println("Original List: \n" + list); //debugging help 
    sort(list); 
    System.out.println("Sorted List: \n" + list); 
} 

}

그리고 여기 컴파일러 오류입니다 :

Sorter.java:16: error: cannot find symbol 
        return a.compareTo(b); 
          ^
    symbol: method compareTo(Object) 
    location: variable a of type Object 
    Sorter.java:31: error: cannot find symbol 
        return a.compareTo(b); 
          ^
    symbol: method compareTo(Object) 
    location: variable a of type Object 
    Sorter.java:34: error: cannot find symbol 
        return a.compareTo(b); 
          ^
    symbol: method compareTo(Object) 
    location: variable a of type Object 
    3 errors 

플레잉 카드의 compareTo 메소드 :

public int compareTo(PlayingCard other) { 
     if (getSuit() < other.getSuit()) { 
      return -1; 
     } 
     else if (getSuit() > other.getSuit()) { 
      return 1; 
     } 
     else { 
      if (getRank() < other.getRank()) { 
       return -1; 
      } 
      else if (getRank() > other.getRank()) { 
       return 1; 
      } 
      else { 
       return 0; 
      } 
     } 
    } 

책의 compareTo 메소드 :

public int compareTo(Book other) { 
     if (getAuthor().compareTo(other.getAuthor()) < 0) { 
      return -1; 
     } 
     else if (getAuthor().compareTo(other.getAuthor()) > 0) { 
      return 1; 
     } 
     else { 
      if (getTitle().compareTo(other.getTitle()) < 0) { 
       return -1; 
      } 
      else if (getTitle().compareTo(other.getTitle()) > 0) { 
       return 1; 
      } 
      else { 
       return 0; 
      } 
     } 
    } 
+0

도서 ''Comparable를 구현하고이 작업을 위해 자신의'공공 INT은 compareTo (도서 otherBook)'방식을 가질 필요가있다. –

+0

답장을 보내 주셔서 감사합니다! Book과 PlayingCard는 모두 Comparable을 구현하고 자체 compareTo 메소드를 가지고 있습니다. –

+0

단락 대신에 실제 컴파일러 출력을 제공 할 수 있습니까? –

답변

0

Object 클래스의 compareTo를 호출하고 있습니다. 클래스 객체 (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html)를 조회하면 해당 메소드가 없다는 것을 알 수 있습니다. 그것이 컴파일러가 말한 것입니다. 비록 "symbol"이라는 단어를 사용하여 메서드 나 필드를 나타 내기는하지만 말입니다.

compareTo를 호출하기 전에 다음 코드와 같이 Integer 또는 Double 인스턴스에 개체를 캐스팅 한 다음 Integer의 compareTo 메서드 나 Double의 compareTo 메서드를 사용할 수 있습니다. :

if(a instanceof Double && b instanceof Double) { 
    Double aDouble = (Double) a; 
    Double bDouble = (Double) b; 
    return aDouble.compareTo(b); 
} 

대부분의 경우 운동은 정수를 Double과 비교하기를 원합니다. 당신이 사용할 수있는 compareTo 메소드를 선택해야하고, 변환과 int/double의 표현을 살펴볼 필요가 있다면 Integer에서 Double로 선택해야합니다. 따라서 다음 중 하나처럼 필요합니다. 옵션 :

if(a instanceof Integer && b instanceof Double) { 
    Integer aInteger = (Integer) a; 
     Double bDouble = (Double) b; 
    return -bDouble.compareTo(aInteger.doubleValue()); //note the negative 
} 

이 또 다른 옵션으로 :

if(a instanceof Double && b instanceof Integer) { 
    Double aDouble = (Double) a; 
     Integer bInteger = (Integer) b; 
    return aDouble.compareTo(bInteger.doubleValue()); 
}