디시인사이드 갤러리

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

갤러리 본문 영역

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

HERMES갤로그로 이동합니다. 2010.11.24 00:52:23
조회 66 추천 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/16 - -
265648 형들 게시판 만들떄 이것중에 어떤게 효율적일까 [3] 꿀레(115.95) 11.08.22 69 0
265647 횽아들~ 연봉 말고 경력별 연봉 차이 질문이라구! [12] 생물학(125.248) 11.08.22 232 0
265646 아까만든 더블클릭하면 페이지 스크롤 최상단 최하단 왔다갔다하는거 laoshanlong갤로그로 이동합니다. 11.08.22 51 0
265645 이직한 회사에서 방금!! [1] 새로운뉴비(116.124) 11.08.22 79 0
265644 삼성이 바다OS만든다니까 LG가 우리는 포기했으니까 .3(124.137) 11.08.22 109 0
265643 근데 컴퓨터 학원 다니면 [2] 오마이갓넬갤로그로 이동합니다. 11.08.22 94 0
265641 내가 생각하기에 지금 OS만든다고 하는게 생각이 별로 없는거 같어 [1] ggm(121.174) 11.08.22 70 0
265640 2000명이 만든 바다가 8명이 만든 안드로이드를 못이겼는데 [2] .3(124.137) 11.08.22 154 0
265639 오늘 첫출근했음 [3] 새로운뉴비(116.124) 11.08.22 97 0
265638 천재해커 이 새끼야 monoless갤로그로 이동합니다. 11.08.22 54 0
265635 그나저나 프갤에는 정보검색 공부하는 사람엄슴? [8] dijkstra(168.115) 11.08.22 105 0
265634 쩐다.. HP 터치패드 99달러 떨이 ㅋㅋㅋㅋㅋㅋ [3] 허허벌판갤로그로 이동합니다. 11.08.22 119 0
265632 스파이 명월 재밌네요! 쿠히히히 [2] y녀6디리(218.146) 11.08.22 58 0
265629 갑인 KT 랑 같은 사무실 쓰는데 [6] 좋은아버지갤로그로 이동합니다. 11.08.22 157 0
265627 십이국기나 그렌라간같은건 어땀? [2] mercedes㉦benz갤로그로 이동합니다. 11.08.22 60 0
265626 내가 컴공이 아닌 전자를 선택한이유는? [1] 개마무사갤로그로 이동합니다. 11.08.22 149 0
265625 이중에 어려운건? [10] 프로k(112.151) 11.08.22 133 0
265624 아오 시발 마취상태 짜증나네 mercedes㉦benz갤로그로 이동합니다. 11.08.22 55 0
265623 한국판 안드로이드 만든다... !![기사] [7] 쿄스케갤로그로 이동합니다. 11.08.22 179 0
265622 아까 내친구가 나한데 회사 자랑했는데 [1] 좋은아버지갤로그로 이동합니다. 11.08.22 55 0
265620 꼬꼬면 먹어본사람? [4] 망함그냥갤로그로 이동합니다. 11.08.22 80 0
265619 지하철역에서 기절해봤냐 [1] !@#ㅇㅇ(211.238) 11.08.22 103 0
265618 정말 아름답구나. [2] 천재해커(175.196) 11.08.22 94 0
265617 vs2010 모델링 도구 써보고 있음.. ㅋㄱ(183.96) 11.08.22 44 0
265616 아 진짜 병특가기싫다 [6] 一ㅡ갤로그로 이동합니다. 11.08.22 123 0
265615 구글뺨치는 민주적인 회사를 상상해봤다 [5] ㅇㅇ(61.77) 11.08.22 146 0
265614 저번에 LG ODD고장나서 서비스센타가서 화를 고래고래 [3] ∫ 2t dt=t²+c갤로그로 이동합니다. 11.08.22 111 0
265611 내 친구의 회사 자랑. [9] 좋은아버지갤로그로 이동합니다. 11.08.22 210 0
265609 스티브잡스가 잘파는거냐 스티브잡스라서 잘팔리는거냐 [1] ㅇㅇ(61.77) 11.08.22 73 0
265606 지금 c++독학하는데 넘 어려우이 [4] cool하니갤로그로 이동합니다. 11.08.22 112 0
265604 hp터치패드 구매대행없음? 一ㅡ갤로그로 이동합니다. 11.08.22 248 0
265602 자바파일요 [3] 자바를..(175.198) 11.08.22 51 0
265601 IT를 진짜 똥으로 보긴하더만 흠좀무(59.14) 11.08.22 123 0
265600 '인문학 소양' 갖춘 SW전문가 뽑는다' [4] (211.255) 11.08.22 130 0
265598 왜 DC만 동영상 링크가 안걸리냐 짜증나게.. McHello갤로그로 이동합니다. 11.08.22 29 0
265588 내가 너의 컴에 바이러스를 심겠다 !!! [5] iljeomobolt갤로그로 이동합니다. 11.08.22 122 0
265586 내가 꿈꾸는 이상적인 IT 현실 [2] 좋은아버지갤로그로 이동합니다. 11.08.22 106 0
265585 솔직히 전산실이나 그런 곳은 코딩 실력 그렇게 안본다 ㅡㅡ [3] 쿄스케갤로그로 이동합니다. 11.08.22 234 0
265580 허세짤 [6] 생각놀이갤로그로 이동합니다. 11.08.22 152 0
265579 첫 직장으로 벤처업체 어떰??? [7] 삼월삼일세시삼십삼분갤로그로 이동합니다. 11.08.22 183 0
265577 예제 다시 간단히 해서 올렸어 HTML DOM [15] 좋은아버지갤로그로 이동합니다. 11.08.22 108 0
265576 DB는 어떻게 공부하나연 [7] Kanon갤로그로 이동합니다. 11.08.22 123 0
265575 흔한 한국의 공대 개그 4.avi [2] 디미준갤로그로 이동합니다. 11.08.22 135 0
265574 blackd 는 봅니다. 좋은아버지갤로그로 이동합니다. 11.08.22 32 0
265573 천재해커가 생각하는 프로그래머의 일상 [4] 천재해커(175.196) 11.08.22 161 0
265572 내가 생각하는 프로그래머의 일상이란.. [7] 프로k(112.151) 11.08.22 158 0
265570 아 도저히 안되겠는데? html 작업중인데 조언 좀해줘 [11] 좋은아버지갤로그로 이동합니다. 11.08.22 84 0
265569 내 생각엔 vb6나 vc6 깔려면 [1] 분당살람갤로그로 이동합니다. 11.08.22 42 0
265567 MFC ´ 멀티스레드 ´ 때문에 걱정 태산.. [12] 뉴비PGM(211.183) 11.08.22 227 0
265566 이거뭐임? 금융권 IT인력 .... [4] 장어구이(211.245) 11.08.22 191 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2