Study/Java

자바 이름과 점수를 입력 받아 순위 출력

토기발 2022. 3. 16. 20:56

임의의 인원과 국어/수학 점수를 입력하여 순위를 출력하는 프로그램을 만들겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
 
public class TestArray {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("인원을 입력 : ");
        int inwon = in.nextInt();
        
        String[] name = new String[inwon];//배열의 크기는 변수로 만들어 줄 수 있다.
        int[] kor = new int[inwon];
        int[] eng = new int[inwon];
        int[] tot = new int[inwon];
        int[] rank = new int[inwon];
        
        for(int i=0; i<inwon; ++i) {
            System.out.print(i+1+"번째 학생 이름 : ");
            name[i] = in.next();
            System.out.print(i+1+"번째 학생의 국어점수 : ");
            kor[i] = in.nextInt();
            System.out.print(i+1+"번째 학생의 영어점수 : ");
            eng[i] = in.nextInt();
            tot[i] = kor[i] + eng[i];
            rank[i] = 1;
        }
        
        for(int i=0; i<inwon; ++i) {//내성적
            for(int j=0; j<inwon; ++j) {//다른사람 성적
                if (tot[i] < tot[j]) {
                    rank[i]++;
                }
            }
        }
        
        for(int i=0; i<inwon; ++i) {
            System.out.println(name[i]+"님의 총점은 " + 
                    tot[i] +"점이고, 순위는 " + rank[i] +"등 입니다.");
        }
    }
}
 
cs
System.out.print("인원을 입력 : ");
int inwon = in.nextInt();
 
인원 변수를 생성합니다.

 

String[] name = new String[inwon];
int[] kor = new int[inwon];
int[] eng = new int[inwon];
int[] tot = new int[inwon];
int[] rank = new int[inwon];

이름/국어점수/영어점수/합계/순위 변수를 배열로 생성합니다.

배열의 크기는 inwon 변수로 만듭니다.

 

 

for(int i=0; i<inwon; ++i) {
System.out.print(i+1+"번째 학생 이름 : ");
name[i] = in.next();
System.out.print(i+1+"번째 학생의 국어점수 : ");
kor[i] = in.nextInt();
System.out.print(i+1+"번째 학생의 영어점수 : ");

 

eng[i] = in.nextInt();
tot[i] = kor[i] + eng[i];

 

이름/국어점수/영어점수를 요청하는 문구를 출력하고 입력값을 각각의 변수에 대입합니다.
합계값은
tot[i] = kor[i] + eng[i]; 로 구합니다.
 
rank[i] = 1;
순위는 우선 모두 1로 초기화합니다.

* 순위를 구하는 방식 *

예를 들어 a, b, c, d가 있을 때

a와 b를 비교하여 a가 더 작은 경우(a<b) 에는 순위를 1 추가합니다.

a가 b보다 더 큰 경우에는 순위를 추가하지 않습니다.

이렇게 a는 그대로 두고 d까지 비교하여 최종 순위를 기록합니다.

a의 순위 비교가 끝나면 b~d도 똑같은 방식으로 비교하여 순위를 기록합니다.

 

for(int i=0; i<inwon; ++i) {
for(int j=0; j<inwon; ++j) {
if (tot[i] < tot[j]) {
rank[i]++;

 

위의 알고리즘으로 코드를 짜면 이렇게 됩니다.

 

 

for(int i=0; i<inwon; ++i) {
System.out.println(name[i]+"님의 총점은 " + tot[i] +"점이고, 순위는 " + rank[i] +"등 입니다.");
}

이름/합계/순위를 출력합니다.

 

잘 출력되었습니다.