반응형
문제
N명의 학생 정보가 있다. 학생 정보는 이름과 성적으로 구분된다. 각 학생의 이름과 성적 정보가 주어졌을 때, 성적이 낮은 순서대로 학생의 이름을 출력하는 프로그램을 작성하시오.
입력 조건
첫번째 줄에 학생의 수 N이 입력된다.
두번째 줄부터 '이름 성적' 과 같이 입력된다.
출력 조건
성적이 낮은 순서대로 출력한다.
풀이
Student 클래스를 생성해 이름과 성적을 멤버 변수로 갖는다. 입력 되는대로 Student 클래스로 이루어진 배열을 생성한다. 그리고 성적 값에 따라 정렬하고 출력한다.
import java.util.*;
class Student implements Comparable<Student> {
private String name;
private int score;
Student (String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return this.name;
}
@Override
public int compareTo(Student student) {
return this.score - student.score;
}
} // end Student class
class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
for (int i = 0; i < n; i++) {
String tmp = sc.nextLine();
String[] input = tmp.split(" ");
String name = input[0];
int score = Integer.parseInt(input[1]);
list.add(new Student(name, score));
}
sc.close();
Collections.sort(list);
for (Student s : list) {
System.out.printf("%s ", s.getName());
}
System.out.println();
} // end main
}
* Student Class는 Comparable 인터페이스를 받아 구현했다. Student 클래스의 멤버변수 중 하나인 score를 통해 정렬하기 위함인데, compareTo() 메서드가 이를 가능하게 한다.
** compareTo() 메서드는 파라미터로 전달된 클래스 객체(비교값)와 현재 객체(기준값)를 비교한다. int 타입을 반환하는데, 기준 값이 큰 경우 양수, 기준 값이 작은 경우 음수, 같은 경우 0을 리턴한다. (오름차순으로 정렬되는데, 내림차순으로 하기 위해서는 값의 위치를 바꿔주면 된다.)
*** List를 통해 값을 받았기 때문에 Arrays.sort가 아닌 Collections.sort를 사용한다.
**** Comparable 말고, Comparator가 존재한다. 정렬 대상인 클래스를 직접 정의할 수 없는 경우 Comparator 객체를 선언하고, compare() 메서드를 오버라이딩한다.
참고자료
'Algorithm' 카테고리의 다른 글
[Algorithm] 부품 찾기 (0) | 2021.05.16 |
---|---|
[Algorithm] 두 배열의 원소 교체 (0) | 2021.05.15 |
[Algorithm] 위에서 아래로 (0) | 2021.05.13 |
[Algorithm] 미로 탈출 (0) | 2021.05.12 |
[Algorithm] 음료수 얼려 먹기 (0) | 2021.05.11 |