-
List 정렬(Comparable, Comparator) 을 이용한 다중 조건 정렬 과제기타/과제 2020. 11. 19. 17:15
다음 조건을 충족해서 표현해보자
1. 10명의 학생.
2. 리스트 항목 이름, 국어점수, 영어점수, 수학점수 .
3. 정렬은 총점이 높은 순서대로 나타낸다.
4. 단, 총점이 같으면 수학성적이 높은 순서대로 나타낸다.
5. 정렬 정책 클래스는 외부파일로 처리한다.TestScore.java
package chap15.sec06; public class TestScore implements Comparable<TestScore>{ String name; int kor; int eng; int math; int total; public TestScore() {} public TestScore(String name, int kor, int eng, int math) { super(); this.name = name; this.kor = kor; this.eng = eng; this.math = math; this.total = kor+eng+math; } @Override public String toString() { return name+": "+ kor + " 영: " + eng + " 수: " + math+ " 총점: " +total+ "\n"; } //사실 이 부분은 왜 있는지 모르겠다. //총점순으로 내림차순 해주는데 지우면 에러가 난다 @Override public int compareTo(TestScore x) { int total = this.total; int total2 = x.total; return total2-total; } }
MathScoreSort.java
package chap15.sec06; import java.util.Comparator; public class MathScoreSort implements Comparator<TestScore>{ int ret = 0; @Override public int compare(TestScore arg0, TestScore arg1) { //총점이 높은 순서로 내림차순해라 if(arg0.total < arg1.total) { ret = 1; }else if(arg0.total > arg1.total) { ret = -1; }else { //만약 총점이 같으면 수학 성적순으로 내림차순해라 if(arg0.math < arg1.math) { ret = 1; }else { ret = -1; } } return ret; } }
TestScoreMain.java
package chap15.sec06; import java.util.*; public class TestScoreMain { public static void main(String[] args) { //리스트 객체를 10개 만들었다 List<TestScore> testList = new ArrayList<>(); testList.add(new TestScore("일일", 67, 89, 50)); testList.add(new TestScore("이이", 50, 89, 67)); testList.add(new TestScore("삼삼", 67, 50, 89)); testList.add(new TestScore("사사", 30, 99, 30)); testList.add(new TestScore("오오", 22, 89, 51)); testList.add(new TestScore("육육", 93, 59, 52)); testList.add(new TestScore("칠칠", 37, 66, 53)); testList.add(new TestScore("팔팔", 66, 82, 33)); testList.add(new TestScore("구구", 27, 89, 80)); testList.add(new TestScore("공공", 17, 79, 56)); //외부 정렬 정책 클래스로 정렬해주기 Collections.sort(testList, new MathScoreSort()); //최종값 System.out.println(testList); } }
결과 값
더보기[삼삼: 67 영: 50 수: 89 총점: 206
, 이이: 50 영: 89 수: 67 총점: 206
, 일일: 67 영: 89 수: 50 총점: 206
, 육육: 93 영: 59 수: 52 총점: 204
, 구구: 27 영: 89 수: 80 총점: 196
, 팔팔: 66 영: 82 수: 33 총점: 181
, 오오: 22 영: 89 수: 51 총점: 162
, 사사: 30 영: 99 수: 30 총점: 159
, 칠칠: 37 영: 66 수: 53 총점: 156
, 공공: 17 영: 79 수: 56 총점: 152
]'기타 > 과제' 카테고리의 다른 글
리눅스 명령어 치트시트 정리 (0) 2021.01.15 2020.11.30 시험문제 풀이 (sql 질의 작성) (0) 2020.11.27 JDBC를 이용해 테이블 만들기 과제2 (0) 2020.11.24 추상클래스와 인터페이스의 정의 및 활용법 (0) 2020.11.24 JDBC를 이용해 Oracle 연동 연습예제 (0) 2020.11.20