디시인사이드 갤러리

갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

이 소스에서 마지막 스튜던트2 크래스는 어떤 기능을 하는거야?

HERMES갤로그로 이동합니다. 2010.11.23 16:30:28
조회 67 추천 0 댓글 0

import java.io.*;
import java.util.*;

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);
                  }
            } // while(true)
      }

      // menu를 보여주는 메서드
      static int displayMenu(){
            System.out.println("**************************************************");
            System.out.println("*                     성적 관리 프로그램                         *");
            System.out.println("*                          version 1.0                               *");
            System.out.println("*                 excerpt from Java의 정석                     *");
            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());

                        if(menu >= 1 && menu <= 4) {
                              break;
                        } else {
                              throw new Exception();
                        }
                  } catch(Exception e) {
                        System.out.println("메뉴를 잘못 선택하셨습니다. 다시 입력해주세요.");
                        System.out.print("원하는 메뉴를 선택하세요.(1~4) : ");
                  }
            } while(true);

            return menu;
      } // public static int displayMenu(){

      // 데이터를 입력받는 메서드
      static void inputRecord() {
            System.out.println("1. 학생성적 입력하기");
            System.out.println("이름,학번,국어성적,영어성적,수학성적\'의 순서로 공백없이 입력하세요.");
            System.out.println("입력을 마치려면 q를 입력하세요. 메인화면으로 돌아갑니다.");

            while(true) {
                 System.out.print(">>");

                 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("입력오류입니다. 이름, 학번, 국어성적, 영어성적, 수학성적\'의 순서로 입력하세요.");
                  }
            } // while(true)
      } // public static void inputRecord() {

      // 데이터를 삭제하는 메서드
      static void deleteRecord() {
            while(true) {
                  displayRecord();
                  System.out.println("삭제하고자 하는 데이터의 학번을 입력하세요.(q:메인화면)");
                  System.out.print(">>");


                   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);
                                                break;
                                          }
                                    } // for(int i=0; i < length; i++) {

                                    if(found) {
                                          System.out.println("삭제되었습니다.");
                                    } else {
                                          System.out.println("일치하는 데이터가 없습니다.");
                                    }
                              } else {
                                    return;
                              }
                  } catch(Exception e) {
                              System.out.println("입력오류입니다. 다시 입력해 주세요.");
                  }
            } // while(true)
      } // public static void deleteRecord() {

      // 데이터를 정렬하는 메서드
      static void sortRecord() {
            while(true) {
                  System.out.print(" 정렬기준을 선탁하세요.(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.print(" 정렬기준을 선탁하세요.(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;
                  }
            } // while(true)
      }

      // 데이터 목록을 보여주는 메서드
      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;
                        mathTotal += student.mathScore;
                        englishTotal += student.englishScore;
                        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+"", 8, Student2.RIGHT)
            );
            System.out.println();
      } // static void displayRecord() {
} // end of class

// 이름을 오름차순(가나다순)으로 정렬하는 데 사용되는 클래스
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 Comparable {
      final static int LEFT = 0;
      final static int CENTER = 1;
      final static int RIGHT = 2;

      String name = "";
      String studentNo = "";
      int koreanScore = 0;
      int mathScore = 0;
      int englishScore = 0;
      int total = 0;

      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 length, int alignment) {
            int diff = length - str.length();
            if(diff < 0) return str.substring(0, length);

            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);
      } // static String format(String str, int length, int alignment) {

      public int compareTo(Object obj) {
            int result = -1;
            if(obj instanceof Student2) {
                  Student2 tmp = (Student2)obj;
                  result = (this.name).compareTo(tmp.name);
            }
            return result;
      }
} // class Student2 implements Comparable {

추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
등록순정렬 기준선택
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 힘들게 성공한 만큼 절대 논란 안 만들 것 같은 스타는? 운영자 24/06/10 - -
232075 ((필독))횽들 비전공자가 들으며 좋은 컴공 수업!! [12] 쉐이킷(123.143) 11.01.24 251 0
232074 노트북중에 말이야 [1] sdfd(61.106) 11.01.24 72 0
232073 야이생키들아 [2] 핫바리(1.99) 11.01.24 85 0
232072 마인크래프트 제작에 쓰인 코드가 몇라인인지 밝혀졌음 [4]    갤로그로 이동합니다. 11.01.24 253 0
232071 레벨디자인(Level Design) 에 대한 고찰 [2] 한마음택배갤로그로 이동합니다. 11.01.24 116 0
232069 살인적이다... [4] 돌아온yoi(124.153) 11.01.24 129 0
232068 안드로이드 구글맵 마커 죤나 많을 때 어캐 쳐리하나요? [3] ㅇㄴㄹ(125.7) 11.01.24 400 0
232067 방학때와 개학때의 차이점 nRESET(211.54) 11.01.24 114 0
232066 자바 하루만 공부해도 마인크래프트 플러그인 만들기 어렵지는 않던데 ㄷㄷ [1] 젤리클갤로그로 이동합니다. 11.01.24 3338 5
232065 상대방아디해킹하는 웹해킹어떤책을 봐야 그나마 쉽게 익힐수있냐? [4] 1Q 430갤로그로 이동합니다. 11.01.24 212 0
232063 쩜오볼트 소환 nRESET(211.54) 11.01.24 40 0
232062 (꾸준글) for 루프가 for..in 루프보다 좋은 이유 [3] kushan갤로그로 이동합니다. 11.01.24 132 0
232061 타자 800타 나오면 뭐해먹을수 있나요? [3] 뿡뿡이(113.59) 11.01.24 196 0
232059 [혐짤] 올린 유;리한님. [8] new gay[max]갤로그로 이동합니다. 11.01.24 168 0
232058 ant 로 빌드 하기 android 히밤(121.166) 11.01.24 105 0
232057 내 어플은 12위임 냉무 [4] 히밤리눅스갤로그로 이동합니다. 11.01.24 123 0
232056 HTML5 캔버스로 간단하게 RPG게임 만들려고하는데... [12] 초보자갤로그로 이동합니다. 11.01.24 248 0
232055 루비나 파이썬이 느리다는 사람들 [40] 히밤리눅스갤로그로 이동합니다. 11.01.24 342 0
232054 횽들 오랜만에 개념 질문 할께여 [5] 에이스1번갤로그로 이동합니다. 11.01.24 122 0
232053 회사에서 수습기간이라는걸 제시하는거 맞죠?? [3] zz(61.43) 11.01.24 131 0
232052 올리디버거 크랙 하실줄 아는사람 도와주세요 [1] 안녕하세요(121.184) 11.01.24 321 0
232050 형드라 마인크래프트가 뭐임? [2] 분당살람갤로그로 이동합니다. 11.01.24 149 0
232049 아, 해결법 알았다. [2]    갤로그로 이동합니다. 11.01.24 103 0
232048 쉬어가는 코너 [2] nRESET(211.54) 11.01.24 71 0
232047 마인크래프트는 오픈소스입니다. [9]    갤로그로 이동합니다. 11.01.24 321 0
232046 64비트인데 64비트로 설치했는데 안되고 32비트하니까된당 [1] 고게이(221.162) 11.01.24 121 0
232045 한글 파렛트 파일을 씌우는것만으로는 안되겠는데.. [8]    갤로그로 이동합니다. 11.01.24 100 0
232044 횽들 파이썬이 C도 대체가 가능해? [14] 초랭이(221.147) 11.01.24 260 0
232043 세상 모든 분야가 경쟁이 쩌러욬ㅋㅋㅋ 갑자원(58.180) 11.01.24 74 0
232041 아...여태껏 헛되게 공부를 해왔나... [1] ㅅㅂ맨날배고픔갤로그로 이동합니다. 11.01.24 100 0
232040 마인크도 자바고 안드로이드 어플도 자바다. [5]    갤로그로 이동합니다. 11.01.24 179 0
232039 마인크래프트 한글화 채팅 나도 작업중인데 [3]    갤로그로 이동합니다. 11.01.24 503 0
232038 LPD3DXSPRITE 이거 쓰는사람 있음?? 달걀소년갤로그로 이동합니다. 11.01.24 147 0
232037 마인크래프트 한글화채팅....... [6] 고게이(221.162) 11.01.24 1491 0
232036 다 필요없어. 필요한것이라곤.. 갑자원(58.180) 11.01.24 65 0
232035 게임제작쪽에 진로를 두고있는데요 질문 몇개.. [5] ㄱㄴㄷ(175.113) 11.01.24 149 0
232033 제가 로또될확률 vs 프로그래머로중소기업취업할확률 vs 공무원시험합격확률 [3] 고3졸업예정(116.39) 11.01.24 173 0
232031 고졸이 대졸 틈바구니에서 살아남을 확률 [3] nRESET(211.54) 11.01.24 168 0
232030 형들 우분투에서 이거 어찌해야함? [3] arx갤로그로 이동합니다. 11.01.24 92 0
232029 테니스 같이 칠 여자 개발자님 구합니다. 테니스짱(174.21) 11.01.24 72 0
232027 전자과는 뭘 공부하면 좋을까요?? [2] 앟앙흥(121.155) 11.01.24 101 0
232026 iljoemobolt 봐라 [1] nRESET(211.54) 11.01.24 85 0
232025 형들 나는 게임업계에서 일하고픈 고3졸업생이야~ [13] 고3졸업예정(116.39) 11.01.24 239 0
232023 진중권 찬양 [8] 물속의다이아갤로그로 이동합니다. 11.01.24 170 0
232022 전형적인 고민형 바보 [5] nRESET(211.54) 11.01.24 131 0
232021 횽들 내 고민 한번 들어볼래욤? [14] 고민닭(112.216) 11.01.24 184 0
232020 조강지처가 좋더라 [1] nRESET(211.54) 11.01.24 105 0
232019 근데 "소스=출력"인 소스 혹시 아는 횽들 없음? [12] ㅇㅇㅇ(121.144) 11.01.24 184 0
232018 그나저나 파이썬은 개사기 ㅡㅡ) [2] 땡칠도사갤로그로 이동합니다. 11.01.24 258 0
232016 냐음 = ω=) 아이패드나 살까 [3] 땡칠도사갤로그로 이동합니다. 11.01.24 122 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2