디시인사이드 갤러리

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

갤러리 본문 영역

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

HERMES갤로그로 이동합니다. 2010.11.24 00:52:23
조회 69 추천 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
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 현역으로 군대 안 간게 의아한 스타는? 운영자 25/06/30 - -
AD 휴대폰 바꿀까? 특가 구매 찬스! 운영자 25/07/02 - -
347752 가산 원룸 좋아? [3] ㅋㄱ(183.96) 13.03.02 155 0
347751 게임회사에 모집같은거 보면 [1] ㅁㄴㅇㄹ(115.92) 13.03.02 195 0
347750 어디서 쓸만한 3d xml모델 구할 수 있을까여.. [4] ㅁㄴㅇㄹ(115.92) 13.03.02 75 0
347749 자바형들 나 궁금한거 있는데 [4] 궁금(121.164) 13.03.02 107 0
347748 형들 피방에서 사양 많이 타는 작업하다 컴 폭발하면 어떻게 되여?? [3] asdf(221.138) 13.03.02 200 0
347745 가만보면 [5] c(175.208) 13.03.02 146 0
347742 매틀랩 고수님 있어요? fft 변환 잘 아시는분~ [3] 도서관(124.0) 13.03.02 311 0
347740 좇중고딩 이하에게 조언(부제 : 너희가 하지 말아야할짓) [1] 삐쭊이(110.70) 13.03.02 138 0
347739 프갤오빠들 사랑해~~♥ [2] DART(110.14) 13.03.02 119 1
347738 게임프로그래밍 공부한다고 해서 c++이랑 쉐이더 이런 공부만 해선 [3] 도레기(221.138) 13.03.02 185 0
347736 형들 IO 개념좀 물어볼게 [9] 해물(124.137) 13.03.02 191 0
347734 좆고딩들 유입요 [1] c(175.208) 13.03.02 74 0
347733 형들 maxscript는 어떻게 공부시ㅏㄱ하는게 좋아여 ㅁㅇㄴㄹ(221.138) 13.03.02 35 0
347732 자바 랑 윈도우 프로그래밍 차이점 알려줘 [3] 아자(121.164) 13.03.02 380 0
347731 자대 대학원 가는거 별론가? ㅇㅇ(210.94) 13.03.02 66 0
347730 자바 독립 os 좀 알려줘여 형들~ [2] 11(121.164) 13.03.02 73 0
347728 ┌열혈c 도전문제 풀다가... [3] 네로시엔갤로그로 이동합니다. 13.03.02 127 0
347727 동적 메모리 할당의 장점에 대해서 찾아봤는데... [9] 네로시엔갤로그로 이동합니다. 13.03.02 199 0
347726 기획가는 문서로 평가받는거지. 하하(1.231) 13.03.02 55 0
347724 일반화하는건 좀 그렇지만, 기획자는 대체로 [2] (168.126) 13.03.02 157 1
347722 자바 배우면 취업 어디로함? [2] 11(121.164) 13.03.02 135 0
347721 형들 영어 어디 까지 배움?? [3] 형들(121.164) 13.03.02 117 0
347720 윈도우 프로그래밍은 어디서 부터 해야 해? 자바(121.164) 13.03.02 37 0
347718 자바스크립트 ~~ 이거 어떻게 쓰는거임 [1] ㄹㅇㄴㅁ(49.143) 13.03.02 101 0
347717 그런데 여기 늅늅들 위에 공지는 읽고 갤질하냐? [1] 생물학(120.50) 13.03.02 61 0
347716 여기에 고딩들 많은듯 이제고2(175.215) 13.03.02 58 0
347714 나도 기획자랑 안좋은적 있었느데 늅늅이(218.153) 13.03.02 65 0
347713 형들 c언어를 공부 하는데 말이야.. [4] 열공(121.164) 13.03.02 158 0
347712 분야가 다르면 모를수도있지. [1] 생물학(120.50) 13.03.02 50 0
347710 프갤 세대 전환인가 생물학(120.50) 13.03.02 75 0
347709 프갤 뉴비인데요 질문하나만 할게요 [3] gana(112.151) 13.03.02 71 0
347704 형동생분들 기획이라는 것에 대해서 어떻게 생각하십니까 [5] DOMINION갤로그로 이동합니다. 13.03.02 142 0
347702 소프트웨어 불법복제방지 프로그램 같은거 말이야 [4] 몰러몰러(211.176) 13.03.02 264 0
347701 개발용 피시 견적 맞추어 봤음.. 조언좀 [5] (222.107) 13.03.02 190 0
347700 26년 본 사람 있냐?? 26년(182.211) 13.03.02 89 0
347698 형들 1초에 여러장 연속 찍을수있는 프로그램 좀 알려주세요. [1] ㄴㅁㅇㄹ(182.215) 13.03.02 106 0
347697 왠지 이럴때 찜찜하지 않냐? [5] ㅁㄴㅇㄹ(121.134) 13.03.02 114 0
347696 님들 원래 윈폼이랑 vba랑 비슷함? [1] (168.126) 13.03.02 65 0
347695 밑에 놈 친구입니다. [4] 데모버젼(119.56) 13.03.02 150 0
347694 c언어 뉴비가 질문하나올립니다... [3] 하면된다(119.56) 13.03.02 160 0
347693 이 정도면 객체 기반 언어에 대한 이해는 다 되어있는 거지? [2] 이정도면(183.107) 13.03.02 109 0
347692 vb 6에서 winhttprequest 썼었는데 요즘 vb에는 이게 없네 [1] dd(59.21) 13.03.02 60 0
347691 이번엔 또 xml이 문제넼ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ 도레기(221.138) 13.03.02 42 0
347690 근데 외국계 회사들이 우리나라 학벌 보기는 함? [1] 궁그미(175.115) 13.03.02 147 0
347689 노예라는걸 느끼게 되는 시점 코알랄(125.186) 13.03.02 95 0
347688 와 프갤러들 갑자기 소름이 돋는다 [5] (175.115) 13.03.02 216 1
347687 Team 잉. - LAN 카드   iη    2012 ! 때릴꺼야?(116.40) 13.03.02 61 0
347686 웹은 레알 진입장벽이 낮다. 넘후 낮다. [2] 하하하(1.231) 13.03.01 170 0
347685 카스퍼스키 입사하기 vs IBM 입사하기 [1] 낄낄이(223.62) 13.03.01 143 0
347684 드림스파크이거 대학생 끝나면 만료됨??? [1] 물구나무(112.148) 13.03.01 76 0
뉴스 '남주의 첫날밤을 가져버렸다' 서현, 충격적인 납치 엔딩! 서현을 납치한 범인은? 궁금증 폭발! 디시트렌드 07.04
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2