본문

성적 계산(JAVA)

반응형

# 성적 계산

JAVA의정석(남궁성 저)에 기재되어있는 예제이다.


source) ScoreEvaluation.java

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
 
public class ScoreEvaluation {
    static ArrayList record = new ArrayList();
    static Scanner s = new Scanner(System.in);
 
    public static void main(String[] args) {
        while (true) {
            switch (displayMenu()) {
            case 1:
                inputRecord();
                break;
            case 2:
                deleteRecord();
                break;
            case 3:
                sortRecord();
                break;
            case 4:
                System.out.println("프로그램을 종료합니다.");
                System.exit(0);
            default:
                break;
            }
        }
    }
 
    // menu를 보여주는 메서드
    private static int displayMenu() {
        System.out.println("*******************");
        System.out.println("* 성적관리 프로그램 *");
        System.out.println("* - version 1.0   *");
        System.out.println("* - Sung han, Lim *");
        System.out.println("*******************");
        System.out.println();
        System.out.println();
        System.out.println("1. 학생성적 입력하기 ");
        System.out.println();
        System.out.println("2. 학생성적 삭제하기 ");
        System.out.println();
        System.out.println("3. 학생성적 정렬하여보기(이름순, 성적순) ");
        System.out.println();
        System.out.println("4. 프로그램 종료");
        System.out.println();
        System.out.println();
        System.out.print("원하는 메뉴를 선택하세요. (1~4) : ");
 
        int menu = 0;
 
        do {
            try {
                menu = Integer.parseInt(s.nextLine().trim());
 
                if (menu >= 1 && menu <= 4) {
                    break;
                } else {
                    throw new Exception();
                }
            } catch (Exception e) {
                System.out.println("메뉴를 잘못 선택하셨습니다. 다시 입력해주세요.");
                System.out.println("원하는 메뉴를 선택하세요.(1~4) : ");
            }
        } while (true);
 
        return menu;
    }
 
    // 데이터를 입력받는 메서드
    private static void inputRecord() {
        System.out.println("1. 학생성적 입력하기");
        System.out.println("'이름,학번,국어성적,영어성적,수학성적'의 순서로 공백없이 입력하세요.");
        System.out.println("입력을 마치려면 q를 입력하세요. 메인화면으로 돌아갑니다.");
 
        while (true) {
            System.out.println(">>");
 
            try {
                String input = s.nextLine().trim();
 
                if (!input.equalsIgnoreCase("q")) {
                    Scanner s2 = new Scanner(input).useDelimiter(",");
 
                    record.add(new Student2(s2.next(), s2.next(), s2.nextInt(), s2.nextInt(), s2.nextInt()));
 
                    System.out.println("입력이 완료되었습니다. 입력을 마치려면 q를 입력하세요");
                } else {
                    return;
                }
            } catch (Exception e) {
                System.out.println("입력오류입니다. '이름, 학번, 국어성적, 영어성적" + ", 수학성적'의 순서로 입력하세요.");
            }
        }
    }
 
    // 데이터를 삭제하는 메서드
    private static void deleteRecord() {
        while (true) {
            displayRecord();
            System.out.println("삭제하고자 하는 데이터의 학번을 입력하세요.(q:메인화면)");
            System.out.println(">>");
 
            try {
                String input = s.nextLine().trim();
 
                if (!input.equalsIgnoreCase("q")) {
                    int length = record.size();
                    boolean found = false;
 
                    for (int i = 0; i < length; i++) {
                        Student2 student = (Student2) record.get(i);
                        if (input.equals(student.studentNo)) {
                            found = true;
                            record.remove(i);
                        }
                    }
 
                    if (found) {
                        System.out.println("삭제되었습니다.");
                    } else {
                        System.out.println("일치하는 데이터가 없습니다.");
                    }
                } else {
                    return;
                }
            } catch (Exception e) {
                System.out.println("입력오류입니다. 다시 입력해 주세요.");
            }
        }
    }
 
    // 데이터를 정렬하는 메서드
    private static void sortRecord() {
        while (true) {
            System.out.println(" 정렬기준을 선택하세요.(1:이름순 2:총점순 3:메인메뉴) : ");
 
            int sort = 0;
 
            do {
                try {
                    sort = Integer.parseInt(s.nextLine());
 
                    if (sort >= 1 && sort <= 3) {
                        break;
                    } else {
                        throw new Exception();
                    }
 
                } catch (Exception e) {
                    System.out.println("유효하지 않은 입력값입니다. 다시 입력해주세요.");
                    System.out.println(" 정렬기준을 선택하세요. (1:이름순 2:총점순 3:메인메뉴) : ");
                }
            } while (true);
 
            if (sort == 1) {
                Collections.sort(record, new NameAscending());
                displayRecord();
            } else if (sort == 2) {
                Collections.sort(record, new TotalDescending());
                displayRecord();
            } else {
                return;
            }
        }
    }
 
    // 데이터 목록을 보여주는 메서드
    private static void displayRecord() {
        int koreanTotal = 0;
        int englishTotal = 0;
        int mathTotal = 0;
        int total = 0;
 
        System.out.println();
        System.out.println("이름 번호 국어 영어 수학 총점 ");
        System.out.println("========================================");
        int length = record.size();
 
        if (length > 0) {
            for (int i = 0; i < length; i++) {
                Student2 student = (Student2) record.get(i);
                System.out.println(student);
                koreanTotal += student.koreanScore;
                englishTotal += student.englishScore;
                mathTotal += student.mathScore;
                total += student.total;
            }
        } else {
            System.out.println();
            System.out.println(" 데이터가 없습니다.");
            System.out.println();
        }
 
        System.out.println("========================================");
        System.out.println("총점: " + Student2.format(koreanTotal + ""11, Student2.RIGHT)
                + Student2.format(englishTotal + ""6, Student2.RIGHT)
                + Student2.format(mathTotal + ""6, Student2.RIGHT) + Student2.format(total + ""6, Student2.RIGHT));
 
        System.out.println();
    }
}
 
// 이름을 오름차순(가나다순)으로 정렬하는 데 사용되는 클래스
class NameAscending implements Comparator {
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Student2 && o2 instanceof Student2) {
            Student2 s1 = (Student2) o1;
            Student2 s2 = (Student2) o2;
 
            return (s1.name).compareTo(s2.name);
        }
        return -1;
    }
}
 
// 총점을 내림차순(큰값에서 작은값)으로 정렬하는 데 사용하는 클래스
class TotalDescending implements Comparator {
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Student2 && o2 instanceof Student2) {
            Student2 s1 = (Student2) o1;
            Student2 s2 = (Student2) o2;
 
            return (s1.total < s2.total) ? 1 : (s1.total == s2.total ? 0 : -1);
        }
        return -1;
    }
}
 
class Student2 implements Comparator {
    final static int LEFT = 0;
    final static int CENTER = 1;
    final static int RIGHT = 2;
    final static int ZERO = 0;
 
    String name = "";
    String studentNo = "";
    int koreanScore = ZERO;
    int englishScore = ZERO;
    int mathScore = ZERO;
    int total = ZERO;
 
    public Student2(String name, String studentNo, int koreanScore, int mathScore, int englishScore) {
        this.name = name;
        this.studentNo = studentNo;
        this.koreanScore = koreanScore;
        this.mathScore = mathScore;
        this.englishScore = englishScore;
        total = koreanScore + mathScore + englishScore;
    }
 
    public String toString() {
        return format(name, 4, LEFT) + format(studentNo, 4, RIGHT) + format("" + koreanScore, 6, RIGHT)
                + format("" + mathScore, 6, RIGHT) + format("" + englishScore, 6, RIGHT) + format("" + total, 8, RIGHT);
    }
 
    static String format(String str, int lengthint alignment) {
        int diff = length - str.length();
        if (diff < 0)
            return str.substring(0length);
 
        char[] source = str.toCharArray();
        char[] result = new char[length];
 
        // 배열 result를 공백으로 채운다.
        for (int i = 0; i < result.length; i++)
            result[i] = ' ';
 
        switch (alignment) {
        case CENTER:
            System.arraycopy(source, 0, result, diff / 2, source.length);
            break;
        case RIGHT:
            System.arraycopy(source, 0, result, diff, source.length);
            break;
        case LEFT:
        default:
            System.arraycopy(source, 0, result, 0, source.length);
        }
        return new String(result);
    }
 
    public int compareTo(Object obj) {
        int result = -1;
        if (obj instanceof Student2) {
            Student2 tmp = (Student2) obj;
            result = (this.name).compareTo(tmp.name);
        }
        return result;
    }
 
    @Override
    public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        return 0;
    }
 
}
cs

 

result)


한 가지 눈여겨 볼만한 부분은 이 예제의 전체적인 구성인데,  main 메서드에서는 프로그램의 전체적인 흐름을 쉽게 알 수 있도록 간결하게 작성하고 실제 각 기능은 별도의 메서드 내에서 처리하였다.

반응형

공유

댓글