디시인사이드 갤러리

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

갤러리 본문 영역

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

HERMES갤로그로 이동합니다. 2010.11.23 16:30:28
조회 69 추천 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/24 - -
235806 심심이 어플은 과연 튜링테스트를 통과할 수 있는가에 대한 철학적 담론 [1] 스택오버플로(114.203) 11.02.24 172 0
235805 프로그래머는 뭘로 돈 버냐? 프로그램 개발해서? [1] 맛효성(61.252) 11.02.24 230 0
235804 git [1] 레시피(114.206) 11.02.23 68 0
235803 님들 웹 개발자 할껀데 드림위버가 도움 되나요? 드림위버 CS4 [1] 플랑이(118.32) 11.02.23 103 0
235802 솔직히 프로그래머 vs 웹디자이너.. 어떤게 더 낫냐? [5] 맛효성(61.252) 11.02.23 216 0
235801 회사 생활 조언좀... [1] ㅋㅋㅋ(175.198) 11.02.23 88 0
235800 백만 팩토리얼 졷뉴비(210.106) 11.02.23 205 0
235799 횽들 뭔가 굉장히 잘못되가는거 같아.. [2] 허허벌판갤로그로 이동합니다. 11.02.23 91 0
235798 프갤러들이 원하는 덕짤판 절대영역 [6] ㅁㅇㅁ(211.117) 11.02.23 222 0
235796 레노버키보드 쓰는 횽들 있음? (175.120) 11.02.23 306 0
235795 바다용 위젯을 하나 만들었는데.. 부락페스티발갤로그로 이동합니다. 11.02.23 61 0
235794 프갤에 현상금 들고 찾아왔쑝.txt [9] 가출한애찾음(116.32) 11.02.23 132 0
235793 One Source - Multi Use 아직은 아니거임? [4] asdf(125.188) 11.02.23 91 0
235791 디시인사이드 앱 테스트 [3] 유리한갤로그로 이동합니다. 11.02.23 214 0
235790 java 우월한가 보네 1위야 [6] 어둠이(118.176) 11.02.23 200 0
235789 C/C++ 가 실무에서 가장 인기있는 언어라는게 사실임??? [6] 어둠이(118.176) 11.02.23 216 0
235788 횽들아 노트북 둘중에 추천좀요 ! [8] 캔시(211.245) 11.02.23 145 0
235787 고속 푸리에 변환으로 구현하는 무한정밀도 [1] 일광면(119.198) 11.02.23 182 0
235786 안뇽? 늅늅 [1] 트리플G갤로그로 이동합니다. 11.02.23 49 0
235784 횽들 비베가 C언어보다 딸리나여? [5] 어둠이(118.176) 11.02.23 143 0
235783 안드로이드 질문염. 재탕 [3] 로이드(218.49) 11.02.23 81 0
235782 '사업 쵸보들의 망상' 에 대하여... 천재플머(175.196) 11.02.23 119 0
235781 머리 아파 -_- [6] 미클갤로그로 이동합니다. 11.02.23 120 0
235780 아오 횽드라 리눅스 입문서좀 [4] 개밥바라기.갤로그로 이동합니다. 11.02.23 149 0
235779 편입 올킬로 재수확정인데, 수능을 다시 볼까? [6] 재수생(124.80) 11.02.23 173 0
235777 아이디어 이딴건 초딩도 가지고 있는거야 [5] 계백(61.255) 11.02.23 112 0
235775 010 6363 6380 연락하실분 해달래요 ㅋㅋㅋㅋ(218.234) 11.02.23 69 0
235774 요즘 백만불짜리 습관 이라는 책을 보고 있는데 [11] \'ㅅ\'(211.222) 11.02.23 134 0
235773 C/C++ 공부하는 좆중딍입니다.... [6] 잉여(111.91) 11.02.23 179 0
235769 매트랩에서 에러뜨는거 해결좀 해주세요ㅠㅠ YJ(99.38) 11.02.23 78 0
235768 횽아들 ebp-4에는 뭐가있어? [2] 김자바(122.202) 11.02.23 82 0
235766 CentOS 네트웤 설정좀 질문드려요.. [2] sosal♡갤로그로 이동합니다. 11.02.23 88 0
235765 임베디드 레시피라는 책 아는 횽 있음??? 하앍하앍(123.199) 11.02.23 437 0
235764 헤드 퍼스트 잡아 이책있자나여.. [4] 뇌자알갤로그로 이동합니다. 11.02.23 107 0
235763 무료 php호스팅 좀 좋은데 없나요? [3] 무료로(112.148) 11.02.23 173 0
235762 튜링머신의 핵심 논제 [2] 스택오버플로(59.22) 11.02.23 108 0
235760 m.boxweb.net 이거는 디씨 갤러리 글 목록 어떻게 보여주는거야? [4] 디씨는(112.148) 11.02.23 91 0
235759 디시는 반성해야된다 [4] 디시는(112.148) 11.02.23 122 0
235758 회사에서 라면을 끓여 먹고 있따 허허벌판갤로그로 이동합니다. 11.02.23 52 0
235757 조바닭님 [1] SODmaster갤로그로 이동합니다. 11.02.23 74 0
235756 디시에는 RSS 없나? [3] 디씨에는(112.148) 11.02.23 157 0
235755 형님들 질문이 있어요 [2] 조홍강존(121.155) 11.02.23 46 0
235754 형들 전문대 컴공 포기하고 전문학교 가려고하는대요 [5] ㅋㅋ(220.120) 11.02.23 361 0
235752 역시 출퇴근이 용이해야...... [3] 이모군(211.40) 11.02.23 90 0
235751 스맛폰에서 바로 실행되는... [2] 궁금해(221.138) 11.02.23 74 0
235750 인터넷이 갑자기 안됩니다 "pc에서 발생하는 패킷으로 인터넷접속장비에~" [5] 고민(115.145) 11.02.23 384 0
235749 신입기준 게임 기획자랑 게임 프로그래머랑 대우차이 심한가여 [4] REX갤로그로 이동합니다. 11.02.23 285 0
235748 자바에서 벡터를 캐스팅할 때, warning을 어떻게 없앨 수 있어? [9] Qs(110.11) 11.02.23 111 0
235747 뭐 그런것들.. iljeomobolt갤로그로 이동합니다. 11.02.23 54 0
235746 관광지용 파노라마 화장실 [1] iljeomobolt갤로그로 이동합니다. 11.02.23 83 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2