디시인사이드 갤러리

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

갤러리 본문 영역

이 소스에서 마지막에 student2클래스가 하는 역할좀 알려줘

HERMES갤로그로 이동합니다. 2010.11.24 00:52:23
조회 67 추천 0 댓글 2


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/09/23 - -
265518 처음으로 사무실 공기가 숨막히다 [2] 좋은아버지갤로그로 이동합니다. 11.08.22 83 0
265517 오토마타 조언좀 [2] EvilAngel갤로그로 이동합니다. 11.08.22 121 0
265515 궁금한게 있는데.. 키보드 비싼거 쓰면 그만큼 좋은점이 있어?? [15] 쿄스케갤로그로 이동합니다. 11.08.22 214 0
265512 수강신청하러 pc방 나왔더니.... [1] 카페엠갤로그로 이동합니다. 11.08.22 93 0
265509 횽들은 키보드 뭐써? [10] 나리링갤로그로 이동합니다. 11.08.22 132 0
265507 잇힝 수강신청 대성공 [3] ∫ 2t dt=t²+c갤로그로 이동합니다. 11.08.22 138 0
265506 여기가 대한민국 IT 의 미래 프갤이냐 ? 좋은아버지갤로그로 이동합니다. 11.08.22 50 0
265503 런링맨에 신세경 나와서 보고 있는데 돋네 [2] 거칠게갤로그로 이동합니다. 11.08.22 223 0
265501 신라면 블랙 맛있냐?? [1] 거칠게갤로그로 이동합니다. 11.08.22 83 0
265499 ㅎㅇ mercedes㉦benz갤로그로 이동합니다. 11.08.22 22 0
265498 -_-)님 [3] 빈민갤로그로 이동합니다. 11.08.22 81 0
265496 컴퓨터가 살짝 구린 맛이 있는데 어떻합니까 [1] 빈민갤로그로 이동합니다. 11.08.22 73 0
265495 [C++ 문제] 공포의 inline의 내부와 효율 [8] 궁금한궁금이(121.129) 11.08.22 130 0
265493 아오 젠장 맥미니가 사양이 딸리나 보다 ㅠㅠ 라이온 + x코드4 [1] 거칠게갤로그로 이동합니다. 11.08.22 107 0
265492 갑자기 궁금한게 컴공과 학교수준차이 심함? [5] +어게인갤로그로 이동합니다. 11.08.22 149 0
265491 난 눈도 안높고 평범한데 왜 나보고 눈이 높다고 그러지?? [1] 거칠게갤로그로 이동합니다. 11.08.22 58 0
265489 아따 x코드4 메모리 해체 안해도 되냐니깨?? [2] 거칠게갤로그로 이동합니다. 11.08.22 73 0
265487 이만 학교를 가기 위해 퇴갤 ㅋ [6] y녀6디리(218.146) 11.08.22 70 0
265486 프갤복습해보니 학원vs대학교 논쟁은 끝이없네 [26] +어게인갤로그로 이동합니다. 11.08.22 219 0
265485 [C] 비트 연산자의 공포 [2] 궁금한궁금이(121.129) 11.08.22 79 0
265484 이런거 좋아하나여 ㅋ [1] y녀6디리(218.146) 11.08.22 76 0
265483 [C++] reinterpret_cast의 위험성 궁금한궁금이(121.129) 11.08.22 40 0
265482 winapi listview컨트롤 잘아시는분? [4] ㅇㅇ(222.234) 11.08.22 72 0
265481 장난 안치고 다시 올린당 [7] 데덴찌갤로그로 이동합니다. 11.08.22 95 0
265480 x코드4에서는 메모리 제거 안해도 되는거야??? 거칠게갤로그로 이동합니다. 11.08.22 35 0
265479 과제 부탁한 새끼 봐랑 C++ 은 클래스를 써야지! [6] 데덴찌갤로그로 이동합니다. 11.08.22 100 0
265478 영어숫자여다리형 평->제곱미터 다만들었어요 [1] 잏힣(210.223) 11.08.22 66 0
265477 조공이란 이런거다 앞으로 질문글은 최소한 이정도의 조공으로 하자 [2] 거칠게갤로그로 이동합니다. 11.08.22 110 0
265476 자바로 opengl을 써서 C정도의 퍼포먼스를 낼 수 있을까? [1] URA!갤로그로 이동합니다. 11.08.22 71 0
265475 근데 C로 짜냐 C++로 짜냐? [3] 데덴찌갤로그로 이동합니다. 11.08.22 74 0
265474 데덴찌횽 조공바칩니다. 헤헤 [9] y녀6디리(218.146) 11.08.22 119 0
265472 y녀6디리 븅신아 너네 진도 어디까지 나갔는지만 말해 [14] 데덴찌갤로그로 이동합니다. 11.08.22 83 0
265471 소스에요 도와주세요.. [12] y녀6디리(218.146) 11.08.22 89 0
265470 도와줘 형들 [10] 자취생(110.13) 11.08.22 71 0
265469 오늘 중으로 과제 끝내야 하는데 제발 도와주십쇼! [4] y녀6디리(218.146) 11.08.22 94 0
265468 방금 커피사러 편의점 갔다가 겪은 이야기.txt [1] 개로그(121.159) 11.08.22 67 0
265467 여자는 xx를 좋아해~ [2] 거칠게갤로그로 이동합니다. 11.08.22 79 0
265466 어셈! 어셈블리어를 공부하자!!!! 거칠게갤로그로 이동합니다. 11.08.22 82 0
265464 형들 근데 이시간에 회사에 있으면 [2] 데덴찌갤로그로 이동합니다. 11.08.22 57 0
265463 이 여자 어떠냐?? 귀염 돋긔~ [1] 거칠게갤로그로 이동합니다. 11.08.22 109 0
265462 정전은 답이 없다 ㅠㅠ 심심해 ㅠㅠ [1] 거칠게갤로그로 이동합니다. 11.08.22 54 0
265460 짤방투척! 데덴찌갤로그로 이동합니다. 11.08.22 62 0
265459 정전겔엔 짤방 투척이 갑이제 [1] 거칠게갤로그로 이동합니다. 11.08.22 66 0
265458 정전겔 프겔을 깨우는 짤방 투척 [5] 거칠게갤로그로 이동합니다. 11.08.22 91 0
265457 <충격> 크리스탈 키스현장 발각 [4] 거칠게갤로그로 이동합니다. 11.08.22 109 0
265456 DB에서 값을 읽어왔는데 [1] 데덴찌갤로그로 이동합니다. 11.08.22 49 0
265455 논리설계 관련해서 실습해볼려는데 쫌 도와줘 [8] 통맥갤로그로 이동합니다. 11.08.22 91 0
265454 그런데 물리학하면 [2] 좋은아버지갤로그로 이동합니다. 11.08.22 66 0
265453 물리학을 복수전공하면 도움이 될까? [4] 잏힣(210.223) 11.08.22 109 0
265452 내가 있자나. [3] 좋은아버지갤로그로 이동합니다. 11.08.22 56 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2