디시인사이드 갤러리

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

갤러리 본문 영역

마지막 스튜던트2 클래스의 역할좀 알려줘

HERMES갤로그로 이동합니다. 2010.11.24 03:07:46
조회 37 추천 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/17 - -
233901 [필독] 게임 제작자를 위한 입법토론회 의견 수렴!!! (모두 읽어주세요 [1] Kimura갤로그로 이동합니다. 11.02.08 126 0
233900 크롬 대박이네.. [4] 허허벌판갤로그로 이동합니다. 11.02.08 208 0
233899 역시 c를 잘하면 존나 멋져보여 [6] po게이wer갤로그로 이동합니다. 11.02.08 308 0
233898 뇌자알횽 [4] 왁스맛치즈갤로그로 이동합니다. 11.02.08 186 0
233896 구피 치어 2마리가 있는대 [4] iljeomobolt갤로그로 이동합니다. 11.02.08 132 0
233895 문외한 [2] 이모군(1.225) 11.02.08 60 0
233894 프로그램 제작 요청하면 라인당 얼마인가요? [4] 하하(118.127) 11.02.08 162 0
233893 안드로이드] 에뮬레이터에서 보이는 지도가 단말기에서 안보이는 이유는? [1] 라르크v(121.158) 11.02.08 119 0
233892 샘숭, 그지같은게 어디 바다같은걸 디밀어? 계백수장군(58.180) 11.02.08 90 0
233891 수학 문제 하나 질문 해봅니다. [3] nRESET(211.54) 11.02.08 132 0
233890 설문조사좀 부탁드릴게요 ㅠㅠ 도와주세요(210.94) 11.02.08 70 0
233889 기발한 광고 [2] LightEach갤로그로 이동합니다. 11.02.08 141 0
233888 이클립스 테마를 구글링해서 받앗는데염 [5] 뇌자알갤로그로 이동합니다. 11.02.08 281 0
233887 샘송 프로그램이 시발 Facebook을 막아놔서 조낸 짜증나네. [5] 물속의다이아갤로그로 이동합니다. 11.02.08 179 0
233886 면접 날짜 잡혔다 +_+ [8] 외계달팽갤로그로 이동합니다. 11.02.08 218 0
233885 코딩하는 시간 [1] (121.184) 11.02.08 116 0
233884 perl 로 유닉스 fmt 기능을 갖고있는 프로그램 만드는 방법좀 알려줘요 [3] misakatsukasa갤로그로 이동합니다. 11.02.08 94 0
233883 [JAVA] 자바 포멧터 질문이요! [4] 스노이스(59.4) 11.02.08 106 0
233882 표준 함수중에서 최댓값 출력해주는 함수 있나요? [3] 온난전선갤로그로 이동합니다. 11.02.08 197 0
233881 aspx확장자 파일이 뭐임? [2] 메디아이(121.148) 11.02.08 182 0
233880 Java 할때... [9] 뇌자알갤로그로 이동합니다. 11.02.08 239 0
233879 으 횽들 장학금 받았어여;; [3] 일광면(119.198) 11.02.08 173 0
233878 램에 대한 전문가분들 질문; [3] (121.133) 11.02.08 79 0
233877 웹표준 [2] 에이스1번갤로그로 이동합니다. 11.02.08 111 0
233875 스크랩 금지입니다. [2] Marley갤로그로 이동합니다. 11.02.08 105 0
233873 아 잣나무 같으니 (푸념) [2] 천회장(211.45) 11.02.08 101 0
233872 배열 나고 포인터낫음? 포인터 나고 배열 낫음? [6] 뇌자알갤로그로 이동합니다. 11.02.08 209 0
233871 땡칠도사횽... [8] 땡칠닭(112.216) 11.02.08 115 0
233870 어휴 저 놈이 또... ㅉㅉㅉ [2] 땡칠도사갤로그로 이동합니다. 11.02.08 143 0
233868 나는 싸고싶다!!! [2] 땡칠도사갤로그로 이동합니다. 11.02.08 207 0
233866 프갤 엉아들아 c언어 개초짜 질문좀 부탁드려요 [4] ㅇㅇ(115.21) 11.02.08 158 0
233864 솔직히 존나 답답 특채해야한다 지랄하는놈들 [2] ㄱㅇ(211.202) 11.02.08 171 0
233863 To jaydeedonuts [3] 생각놀이갤로그로 이동합니다. 11.02.08 87 0
233862 고교생 해커...... [3] 캐닭(112.216) 11.02.08 298 0
233861 해커들이 양산될수록 뜨는 분야 [8] 계백수장군(61.255) 11.02.08 337 0
233860 IT 3년 경력이랑 기계공학 학사로 뭐 먹고살수있나여? [4] 켁큇갤로그로 이동합니다. 11.02.08 252 0
233859 아나 샹그릴라같은 디씨 - _-) [1] 땡칠도사갤로그로 이동합니다. 11.02.08 104 0
233858 2분마다 알람울리는 프로그램 없으면 만들어줘 [11] jaydeedonuts갤로그로 이동합니다. 11.02.08 305 0
233855 퇴사를 위해 3시간 동안이나 얘기하다 왔어. [4] 물속의다이아갤로그로 이동합니다. 11.02.08 234 0
233852 고교생 해커에 외국정부ㆍ기업 줄줄이 `구멍' [6] 왁스맛치즈갤로그로 이동합니다. 11.02.08 301 0
233851 옆에 과장님 매니지드 c++로 뭐한다고 하는것 같은데 [1] .3(124.137) 11.02.08 99 0
233850 VirtualAlloc함수가 할당하는 메모리의 위치가 어디죠??? 컴돌이(58.77) 11.02.08 88 0
233849 구글엔 자바스크립트 고수가 서식하는듯 [5] ㄱㄱ(61.107) 11.02.08 241 0
233847 이건 뭐라고 설명해야할까.... [1] 땡칠도사갤로그로 이동합니다. 11.02.08 116 0
233846 다펑 마우스 공략 유리한갤로그로 이동합니다. 11.02.08 93 0
233845 동생이 컴퓨터공학과를 갓는데여 [7] 실특마지막갤로그로 이동합니다. 11.02.08 246 0
233844 웹사이트 취약점 진단 초급과정,HTTP의 이해,모의해킹 실습 Choongang(125.129) 11.02.08 182 0
233842 수강신청 성공 ㅋ [1] [성대아싸]갤로그로 이동합니다. 11.02.08 98 0
233841 니들 벡터맨에 엄지원 나왔던 건 알고 갤질함? [3] 분당살람갤로그로 이동합니다. 11.02.08 199 0
233840 컴퓨터 하드웨어과목 이거 뭐하는거지 [2] 꿀레(14.33) 11.02.08 88 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2