2014-03-05 3 views
0

배열의 개체를 내림차순으로 정렬 할 수 있도록 배열의 개체를 속성별로 비교하려고했습니다. 다음 샘플 코드는 다음과 같습니다 배열이 Candidate[][]정렬을 위해 배열 내부의 개체 비교

System.out.println("How many positions for this election? > "); 
    numberOfPositions = sc.nextInt(); 
    Candidate Candidate[][] = new Candidate[numberOfPositions][]; 
    PoliticalParty Parties[][] = new PoliticalParty[numberOfPositions][]; 
    for(int i=0;i<numberOfPositions;i++){ 
     String name; 
     String politicalParty; 
     System.out.println("Enter position name > "); 
     position = sc.next(); 
     System.out.println("How many seats? > "); 
     numberOfSeats = sc.nextInt(); 
     System.out.println("How many candidates? > "); 
     numberOfCandidates = sc.nextInt(); 
     Candidate[i] = new Candidate[numberOfCandidates+1]; 
     Candidate[i].sort(votes); //<--------------------------This is what im trying// 

식에서 (투표)이 코드를 사용하여 텍스트 파일에서 파생 된 INT는 다음과 같습니다

System.out.println("Enter file name > "); 
    filename = sc.next(); 
    try { 
     filescan = new Scanner(new File(filename)); 
    } catch (FileNotFoundException ex) { 
     //Logger.getLogger(Election.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    String L = System.lineSeparator(); 
    filescan.useDelimiter(L); 
    while (filescan.hasNext()) { 
     numberOfVoters++; 
     line = filescan.next(); 
     for(int x=0,j=0;j<line.length();j++){ 
      switch(line.charAt(j)){ 
       case ',': 
        x++; 
        break; 
       case ' ': 
        break; 
       default: 
        int y = line.charAt(j)-48; 
        //Integer.parseInt(line.charAt(j).toString()); 
        Candidate[x][y].addVote(); 
        break; 
      } 
     } 

(투표는) 다른 클래스에 캡슐화되어있어서,

public class Candidate{ 
int votes = 0; 
String politicalParty; 

public Candidate(String name, String politicalParty) { 
    super(name); 
    this.politicalParty = politicalParty; 
} 

public void addVote() { 
    this.votes++; 
    //return votes; 
} 

public int getVotes() { 
    return votes; 
} 

@Override 
public String getName() { 
    return getName(); 
} 

public void displayFields(){ 
    System.out.println(this.getName() + " (" + getPoliticalParty() + ") - " + votes); 
} 

public String getPoliticalParty() { 
    return politicalParty; 
} 

public void setPoliticalParty(String politicalParty) { 
    this.politicalParty = politicalParty; 
} 
} 
+0

비교 가능 인터페이스 http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html – Averroes

답변

1

배열은 미리 만들어진 정렬 방법이있다. Javadoc for Arrays.sort(Object[] a)은 "자연 순서"를 언급합니다. Comparable 인터페이스는 자연 순서를 제공하기 위해 존재합니다.

단계

1 클래스에 인터페이스를 적용합니다.

  • public class Candidate implements Comparable<Candidate> {

단계 2

은 클래스의 compareTo(Candidate c) {} 방법을 구현합니다.

Javadoc forcompareTo() 계약서를 읽으십시오. 일반적으로 this.property이 각각 c.property보다 크거나 같거나 작은 경우 양수, 0 또는 음수를 반환해야합니다. property은 비교 대상 분야입니다.

  • 팁 : property가 문자열 인 경우, 당신은 단순히 다시 사용할 수있는 문자열의 compareTo()
    • return this.property.compareto(c.property);
  • 팁 : property가 (투표와 같은) 정수의 경우, 당신은 영리 긍정적 만들 수 있습니다, 차이를 취함으로써 0 또는 음수로 변환합니다.
  • return this.votes - c.votes;

단계 정렬 배열 3

.

개체가 비슷해 졌으므로 컬렉션이있는 경우 Collections.sort(list)이나 개체 배열이있는 Arrays.sort(list)을 호출하십시오.

0

나는 당신이 정렬 할 수있는 요소를 저장하기 위해 ArrayList에를 사용하고 다음 두 가지 옵션이 있습니다 추천 : (INTERF 항목에 Comparable (인터페이스)를 만들거나 비교기를 만들 에이스) :

public class Candidate implements Comparable<Candidate> { 
    ... 

public int compareTo(Candidate c) { 
    ... //compare here the attributes of this and c 
} 

}

0

빠른 질문에 짧은 대답 : java.util.Arrays.sort()

+0

'Comparator'가 누락되었거나 'Comparable'을 구현하지 못했습니다. –

+0

생각해 보면 OP가 그걸 꽤 빨리 알아낼 수있을 것 같네요 :) – JimmyB

0
  1. 변수가 대문자로 시작하는 이유는 무엇입니까? 그것은 작은 변수의 모든 변수와 같아야합니다.
  2. 사용자 정의 데이터 유형을 저장하기 위해 콜렉션을 사용해야하며, Collections.sort(List<T> list, Comparator<? super T> c)을 사용하여 쉽게 정렬하고 원하는대로 사용자 정의 Comparator을 정의 할 수 있습니다.