서른세 번째 수업

정혅·2024년 3월 30일

더 조은 아카데미

목록 보기
38/76
post-thumbnail

오전문제

Stack

괄호가 제대로 있는지 없는지 검사

package com.test.memo;

import java.util.EmptyStackException;
import java.util.Stack;

public class Practice {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage : java ExpValidCheck \"EXPRESSION\"");
            System.out.println("Example : java ExpValidCheck \"((2+3)*1)+3\"");
        }
        String expression = args[0];
        System.out.println("expression: " + expression);

        Stack<Character> st = new Stack<>();
        try {
            for (int i = 0; i < expression.length(); i++) {
                char ch = expression.charAt(i);

                if (ch == '(') {
                    st.push(ch);
                } else if (ch == ')') {
                    st.pop(); // 가장 위에있는 요소 제거되고 반환
                }
            }
            if (st.isEmpty()) {
                System.out.println("괄호가 일치합니다.");
            } else
                System.out.println("괄호가 일치하지 않습니다.");

        } catch (EmptyStackException e) {
            System.out.println("괄호가 일치하지 않습니다.");
        }
    }
}


Queue

입력한 문자열 저장해서 순대로 꺼내

package com.test.memo;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Practice {

    static Queue q = new LinkedList();
    static final int MAX_SIZE = 5; // Queue에 최대 5개까지만 저장되도록 한다.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("help를 입력하면 도움말을 볼 수 있습니다.");

        while (true) {
            System.out.print(">>");
            try {

                String input = sc.nextLine().trim();

                if (" ".equals(input))
                    continue;
                if (input.equalsIgnoreCase("q")) {
                    System.exit(0);
                    sc.close();
                } else if (input.equalsIgnoreCase("help")) {
                    System.out.println("help - 도움말을 보여줍니다.");
                    System.out.println("q 또는 Q - 프로그램을 종료합니다.");
                    System.out.println("history - 최근에 입력한 명령어를 5개 보여줍니다.");
                } else if (input.equalsIgnoreCase("history")) {

                    save(input); // 큐에 사용자의 입력을 저장하기 위해서

                    LinkedList<String> tmp = (LinkedList<String>) q;// queue를 linkedlist로 형변환
                    Iterator<String> it = tmp.iterator();

                    int i = 0;
                    while (it.hasNext()) {
                        System.out.println(++i + " . " + it.next());
                    }
                } else {
                    save(input);
                    System.out.println(input);
                }
            } catch (Exception e) {
                System.out.println("입력 오류입니다.");
            }
        }
    }

    static void save(String input) {
        // queue에 저장
        if (!"".equals(input)) { // input이 빈 문자열이 아니면
            q.offer(input);
        } else if (q.size() > MAX_SIZE) {
            q.remove();
        }
    }
}


List

다음의 실행결과를 적으시오

다음의 실행결과를 적으시오.

import java.util.*;

class ListIteratorEx1 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");

        ListIterator it = list.listIterator();

        while(it.hasNext()) {
            System.out.print(it.next()); // 순방향으로 진행하면서 읽어온다.
        }
        System.out.println();

        while(it.hasPrevious()) {
            System.out.print(it.previous()); // 역방향으로 진행하면서 읽어온다.
        }
        System.out.println();
    }
}
  • 1 2 3 4 5

    5 4 3 2 1


HashSet / LinkedList 로또번호

package com.test.memo;

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;

public class Practice {

    public static void main(String[] args) {
        HashSet<Integer> set = new HashSet<>();

        for (int i = 0; i < 6; i++) {
            set.add((int) (Math.random() * 45) + 1);
        }
        LinkedList<Integer> list = new LinkedList<>(set);
        Collections.sort(list);

        System.out.println(list);
    }
}

32일차 예제 참고


TreeSet 예제

범위 나누기

import java.util.*;

class TreeSetEx2 {
    public static void main(String[] args) {
        TreeSet set = new TreeSet();
        int[] score = {80, 95, 50, 35, 45, 65, 10, 100};

        for(int i=0; i < score.length; i++)
//            set.add(new Integer(score[i]));
            set.add(Integer.valueOf(score[i]));
//            set.add(score[i]); 이렇게도 가능 자동 오토박싱/언박싱

//        System.out.println("50보다 작은 값 :"    + set.headSet(new Integer(50)));
//        System.out.println("50보다 큰 값 :"    + set.tailSet(new Integer(50)));
        System.out.println("50보다 작은 값 :"    + set.headSet(Integer.valueOf(50)));
        System.out.println("50보다 큰 값 :"    + set.tailSet(Integer.valueOf(50)));
    }
}
/*
50보다 작은 값 :[10, 35, 45]
50보다 큰 값 :[50, 65, 80, 95, 100]
*/

/*
headSet 메서드와 tailSet메서드를 이용하면, TreeSet에 저장된 객체 중 지정된 기준
값보다 큰 값의 객체들과 작은 값의 객체들을 얻을 수 있다.
*/
  • tailSet() : 들어가있는 인자보다 큰 값

  • headSet(): 들어가있는 인자보다 작은 값


HashMap

HashTable(구)보다 HashMap(신) 을 사용하는게 좋다. > HashTable은 동기화가 되서 성능이 떨어짐

저장순서를 유지하려면 LinkedHashMap을 사용하면 된다.

  • 보통 key를 String 으로 제네릭타인으로 둔다.

properties - HashTable의 하위 클래스

HashTable을 상속받아 구현 - 환경설정할때 많이 쓰인다.

  • key를 String, value도 String으로 둔다.

메서드

import java.io.*;
import java.util.*;

class PropertiesEx2 {
    public static void main(String[] args) {
        // commandline에서 inputfile을 지정해주지 않으면 프로그램을 종료한다.
        if(args.length != 1) {
            System.out.println("USAGE: java PropertiesEx2 INPUTFILENAME");
            System.exit(0);
        }

        Properties prop = new Properties();

        String inputFile = args[0];//input.txt

        try {
            prop.load(new FileInputStream(inputFile));
        } catch(IOException e) {
            System.out.println("지정된 파일을 찾을 수 없습니다.");
            System.exit(0);
        }

        String   name = prop.getProperty("name");

//        try {
//            name = new String(name.getBytes("8859_1"), "EUC-KR");
//        } catch(Exception e) {}

        String[] data = prop.getProperty("data").split(",");//split(",")은 컴마를 기준으로 배열을 생성 
        int max = 0;
        int min = 0;
        int sum = 0;

        for(int i=0; i < data.length; i++) {
            int intValue = Integer.parseInt(data[i]);
            if (i==0) max = min = intValue;

            if (max < intValue) {
                max = intValue;
            } else if (min > intValue) {
                min = intValue;
            }

            sum += intValue;
        }

        System.out.println("이름 :"  + name);        
        System.out.println("최대값 :" + max);
        System.out.println("최소값 :" + min);
        System.out.println("합계 :"  + sum);
        System.out.println("평균 :"  + (sum*100.0/data.length)/100);
    }
}
/*
실행 예
java PropertiesEx2 input.txt
이름 :Seong Namkung
최대값 :35
최소값 :1
합계 :111
평균 :11.1
*/
/*
외부파일(input.txt)로부터 데이터를 입력받아서 계산결과를 보여주는 예제이다. 외부파
일의 형식은 라인단위로 키와 값이 '='로 연결된 형태이어야 하며 주석라인은 첫 번째
문자가 '#'이어야 한다.
 정해진 규칙대로만 파일을 작성하면 load()를 호출하는 것만으로 쉽게 데이터를 읽어 올
수 있다. 다만 인코딩(encoding)문제로 한글이 깨질 수 있기 때문에 한글을 입력받으려면
아래와 같이 코드를 변경해야한다.

String name = prop.getProperty("name");

try{
    name = new String(name.getBytes("8859_1"), "EUC-KR");
} catch(Exception e) {}

파일로부터 읽어온 데이터의 인코딩을 라팅문자집합(8859_1)에서 한글완성형(EUC-KR
또는 KSC5601)으로 변환해주는 과정을 추가한 것이다. 우리가 사용하고  있는 OS의 
기본 인코딩(encoding)이 유니코드가 아니라서 이런 변환이 필요한 것이라는 것만 
이해하고 넘어가자
[참고] key에 문자 '='를 포함시키고자 한다면 escape 문자 '\'를 사용하여 '\='와
같이 표현한다.
*/
  • 파일 입출력은 반드시 예외처리를 해야한다.

  • input.txt내욜

    #이것을 주석

    #여러줄도 가능

    name = 홍길동

    data = 9,1,5,2,8~

예제 2

import java.util.*;

class PropertiesEx1 {
    public static void main(String[] args) {
        Properties prop = new Properties();

        // prop에 키와 값(key, value)을 저장한다. > 모두 String 
        prop.setProperty("timeout","30");
        prop.setProperty("language","kr");
        prop.setProperty("size","10");
        prop.setProperty("capacity","10");

        // prop에 저장된 요소들을 Enumeration을 이용해서 출력한다. > Iterator의 구버전 = Enumeration 
        Enumeration e = prop.propertyNames();

        while(e.hasMoreElements()) {
            String element = (String)e.nextElement();
            System.out.println(element + "="+ prop.getProperty(element));
        }

        System.out.println();
        prop.setProperty("size","20");    // size의 값을 20으로 변경한다.
        System.out.println("size="       + prop.getProperty("size"));
        System.out.println("capacity="   + prop.getProperty("capacity", "20"));
        // String getProperty(String key, String defaultValue)
        // 지정된 키(key)의 값(value)를 반환한다. 키를 못찾으면
        // defaultValue를 반환한다. > capacity가 있으면 10, 없으면 20 (ㅇ)
        System.out.println("loadfactor=" + prop.getProperty("loadfactor", "0.75"));
                                                            //setProperty에 loadfactor가 없으니까 0.75(defaultValue)를 가져온다  
        System.out.println(prop);    // prop에 저장된 요소들을 출력한다.
        prop.list(System.out);      // prop에 저장된 요소들을 화면(System.out)에 출력한다.
    }
}


/*
capacity=10
size=10
timeout=30
language=kr

size=20
capacity=10
loadfactor=0.75
//출력 
{size=20, language=kr, timeout=30, capacity=10}

-- listing properties --
size=20
language=kr
timeout=30
capacity=10
*/

/*
Properties의 기본적인 메서드를 이용해서 저장하고 읽어오고 출력하는 방법을 보여주는
간단한 예제이다. 데이터를 저장하는데 사용되는 setProperty()는 단순히 Hashtable의
put메서드를 호출할 뿐이다. 그리고  setProperty()는 기존에 같은 키로 저장된 값이 있는
경우 그 값을 Object타입으로 반환하며, 그렇지 않을 때는 null을 반환한다.

Object setProperty(String key, String value)

getProperty()는 Properties에 저장된 값을 읽어오는 일을 하는데, 만일 읽어오려는 키가
존재하지 않으면 지정된 기본값(defaultValue)을 반환한다.

String getProperty(String key)
String getProperty(String key, String defaultValue)

Properties는 Hashtable을 상속받아 구현한 것이라 Map의 특성상 저장순서를 유지하지
않기 때문에 예제의 결과에 출력된 순서가 저장순서와는 무관하다는 것을 확인하자.
 Properties는 컬렉션프레임웍 이전의 구버전이므로 Iterator가 아닌 Enumeration을
사용한다. 그리고 list메서드를 이용하면 Properties에 저장된 모든 데이터를 화면
또는 파일에 편리하게 출력할 수 있다.

void list(PrintStream out)
void list(PrintWriter out)

System.out은 화면과 연결된 표준출력으로 System클래스에 정의된 PrintStream타입의
static 변수이다.
*/

예제 3 - 외부 파일에 주석으로 내용 저장하기

import java.util.*;
import java.io.*;

class PropertiesEx3 {
    public static void main(String[] args) {
        Properties prop = new Properties();

        prop.setProperty("timeout","30");
        prop.setProperty("language","한글");
        prop.setProperty("size","10");
        prop.setProperty("capacity","10");

        try {
            prop.store(new FileOutputStream("output.txt"), "Properties Example");//""사이의 내용을  output.txt에 주석으로 저장한다. 
            prop.storeToXML(new FileOutputStream("output.xml"),  "Properties Example");
        } catch(IOException e) {
            e.printStackTrace();        
        }
    } // main의 끝
}

/*
이전 예제와는 반대로 Properties에 저장된 데이터를 store()와 storeToXML()를 이용해서
파일로 저장하는 방법을 보여 준다. 
*/

예제 4 - 시스템 속성 가져오기

import java.util.*;

class PropertiesEx4{
    public static void main(String[] args) {
        Properties sysProp = System.getProperties();
        System.out.println("java.version :" + sysProp.getProperty("java.version"));//내 컴퓨터의 java버전을 가져온다. 
        System.out.println("user.languag :" + sysProp.getProperty("user.language"));
        sysProp.list(System.out);
    }
}

/*
시스템 속성을 가져오는 방법을 보여주는 예제이다. System클래스의 getProperties()를
호출하면 시스템과 관련된 속성이 저장된 Properties를 가져올 수 있다. 이 중에서 원하는
속성을 getProperty()를 통해 얻을 수 있다.
 이 예제를 실행시켜보고 어떠한 속성들이 있는지 살펴보고 어떤 속성을 통해 어떤 값을
얻을 수 있는지 확인하도록 하자.
*/

Collections

예제1

import java.util.*;
import static java.util.Collections.*;

public class CollectionsEX {

    public static void main(String[] args) {
        List list = new ArrayList();
        System.out.println(list);
        // []

        addAll(list, 1,2,3,4,5);
        System.out.println(list);
        // [1, 2, 3, 4, 5]

        rotate(list, 2);    // 오른쪽으로 두 칸씩 이동
        System.out.println(list);
        // [4, 5, 1, 2, 3]

        swap(list,0,2);        // 첫 번째와 세 번째를 교환(swap)
        System.out.println(list);
        // [1, 5, 4, 2, 3]

        shuffle(list);        // 저장된 요소의 위치를 임의로 변경
        System.out.println(list);
        // [1, 3, 4, 5, 2]

        sort(list);            // 정렬
        System.out.println(list);
        // [1, 2, 3, 4, 5]

        sort(list, reverseOrder());        // 역순 정렬 reverse(list);와 동일
        System.out.println(list);
        // [5, 4, 3, 2, 1]

        int idx = binarySearch(list, 3);    // 3이 저장된 위치(index)를 반환
        System.out.println("index of 3 = " + idx);
        // index of 3 = 2

        System.out.println("max=" + max(list));        // max=5
        System.out.println("min=" + min(list));        // min=1
        System.out.println("min=" + max(list, reverseOrder()));        // min=1

        fill(list, 9);        // list를 9로 채운다.
        System.out.println("list="+list);
        // list=[9, 9, 9, 9, 9]

        // list와 같은 크기의 새로운 list를 생성하고 2로 채운다. 단, 결과는 변경불가
        List newList = nCopies(list.size(), 2);
        System.out.println("newList="+newList);
        // newList=[2, 2, 2, 2, 2]

        System.out.println(disjoint(list, newList)); // 공통요소가 없으면 true
        // true

        copy(list, newList);//list를 newList로 복사했으니 list가 2,2,2,2로 변경된다. 
        System.out.println("newList="+newList);
        // newList=[2, 2, 2, 2, 2]
        System.out.println("list"+list);
        // list[2, 2, 2, 2, 2]

        replaceAll(list, 2, 1);
        System.out.println("list="+list);
        // list=[1, 1, 1, 1, 1]

        Enumeration e = enumeration(list);    // list를 Enumeration로 변환
        ArrayList list2 = list(e);        // Enumeration을 ArrayList로 변환

        System.out.println("list2"+list2);
        // list2[1, 1, 1, 1, 1]
    }
}

/*
지네릭스는 JDK1.5부터 도입된 기능이므로 JDK1.5이전에 작성된 코드를 사용할 때는
이 메서드들이 필요할 수 있다.
*/
  • 만약Collections 를 import해오지 않았다면 addAll()메서드를 사용할 때 Collections.addAll() 로 사용해야한다.

자바의 정석 Chapter11문제

  1. 정수집합 1, 2, 3, 4와 3, 4, 5, 6의 교, 차, 합집합을 구하는 코드로 다음과 같은 결과를 출력해라

내가 푼 코드

package com.test.memo;

import java.util.ArrayList;

public class Practice {

    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList();
        ArrayList<Integer> list2 = new ArrayList();

        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);

        list2.add(3);
        list2.add(4);
        list2.add(5);
        list2.add(6);

        ArrayList<Integer> hap = new ArrayList(list1);
        hap.addAll(list2);

        ArrayList<Integer> kyo = new ArrayList(list1);
        kyo.retainAll(list2);

        ArrayList<Integer> cha = new ArrayList(list1);
        cha.removeAll(list2);

        System.out.println("list1=" + list1);
        System.out.println("list2=" + list2);
        System.out.println("hap=" + hap);
        System.out.println("kyo=" + kyo);
        System.out.println("cha=" + cha);
    }
}


  1. 아래 코드의 실행결과를 적으시오

  • 7 6 3 2

  1. 다음 중 에서 제일 비용이 많이 드는 작업은?? 단, 작업 도중에 ArrayList 의 크기 변경이 발생하지 않는다고 가정한다.

a. 첫 번째 요소 삭제

b. 마지막 요소 삭제

c. 마지막에 새로운 요소 추가

d. 중간에 새로운 요소 추가

  • d

틀림

  • 5번째

정답

  • 6번째


내가 푼 코드- 정답

package com.test.memo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

class Student implements Comparable<Student> {
    String name;
    int ban;
    int no;
    int kor, eng, math;

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    int getTotal() {
        return kor + eng + math;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage();
    }

    String getName() {
        return name;
    }

    @Override
    public int compareTo(Student o) {
        return this.getName().compareTo(o.getName());
    }
}

public class Practice {

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList();

        list.add(new Student("홍길동", 1, 1, 100, 100, 100));
        list.add(new Student("남궁성", 1, 2, 90, 70, 80));
        list.add(new Student("김자바", 1, 3, 80, 80, 90));
        list.add(new Student("이자바", 1, 4, 70, 90, 70));
        list.add(new Student("안자바", 1, 5, 60, 100, 80));
        Collections.sort(list);
        Iterator it = list.iterator();
        while (it.hasNext())
            System.out.println(it.next());
    }
}


내가 푼 코드 - 정답

package com.test.memo;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

class Student implements Comparable {
    String name;
    int ban, no, kor, eng, math;

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    int getTotal() {
        return kor + eng + math;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage();
    }

    public int compareTo(Object o) {
        if (o instanceof Student) {
            Student tmp = (Student) o;
            return name.compareTo(tmp.name);
        } else {
            return -1;
        }
    }
} // class Student

public class Practice {
    static int getGroupCount(TreeSet set, int from, int to) {
        Student s1 = new Student("from", 0, 0, from, from, from);
        Student s2 = new Student("to", 0, 0, to, to, to);
        return (set.subSet(s1, s2)).size();
    }

    public static void main(String[] args) {
        TreeSet<Student> set = new TreeSet<Student>(new Comparator<Student>() {
            public int compare(Student o1, Student o2) {
                return (int) (o1.getAverage() - o2.getAverage());
            }
        });
        set.add(new Student("홍길동", 1, 1, 100, 100, 100));
        set.add(new Student("남궁성", 1, 2, 90, 70, 80));
        set.add(new Student("김자바", 1, 3, 80, 80, 90));
        set.add(new Student("이자바", 1, 4, 70, 90, 70));
        set.add(new Student("안자바", 1, 5, 60, 100, 80));

        Iterator it = set.iterator();
        while (it.hasNext())
            System.out.println(it.next());

        System.out.println("[60~69]:" + getGroupCount(set, 60, 70));
        System.out.println("[70~79]:" + getGroupCount(set, 70, 80));
        System.out.println("[80~89]:" + getGroupCount(set, 80, 90));
        System.out.println("[90~100]:" + getGroupCount(set, 90, 101));

    }
}


내가 푼 풀이 - 정답

package com.test.memo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

class Student {
    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    int getTotal() {
        return kor + eng + math;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage();
    }

    int getBan() {
        return ban;
    }

    int getNo() {
        return no;
    }
}// class Student

class BanNoAscending implements Comparator<Student> {
    public int compare(Student o1, Student o2) {
        if (o1.getBan() == o2.getBan()) {
            return o1.getNo() - o2.getNo();
        } else {
            return o1.getBan() - o2.getBan();
        }

    }
}

public class Practice {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList();//ArrayList는 직접적으로 정렬을 수행할 수 없다. 

        list.add(new Student("이자바", 2, 1, 70, 90, 70));
        list.add(new Student("안자바", 1, 2, 80, 80, 90));
        list.add(new Student("홍길동", 2, 2, 60, 100, 80));
        list.add(new Student("남궁성", 1, 3, 100, 100, 100));
        list.add(new Student("김자바", 1, 1, 90, 70, 80));

        Collections.sort(list, new BanNoAscending());

        Iterator it = list.iterator();

        while (it.hasNext())

            System.out.println(it.next());
    }
}

  • COllections클래스의 sort()메서드를 사용해 정렬할 수 있다. 만약 익명클래스로 사용하고싶다면 Collections.sort()를 사용해 익명클래스로 구현할 수 있다.

내가 푼 풀이 - 틀림

package com.test.memo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class Student implements Comparable<Student> {
    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;
    int total; // 총점
    int schoolRank; // 전교등수

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;

        total = kor + eng + math;
    }

    int getTotal() {
        return total;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    public int compareTo(Student o) {// 총점을 기준으로 내림차순
        return this.getTotal() - o.getTotal();

    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage()
                + "," + schoolRank; // 새로추가
    }
}// class Student

public class Practice {
    public static void calculateSchoolRank(List list) {

        Collections.sort(list);// 먼저 list를 총점기준 내림차순으로 정렬한다.

        int prevRank = -1; // 이전 전교등수
        int prevTotal = -1; // 이전 총점
        int length = list.size();

        Iterator<Student> it = list.iterator();

        int sameRank = 0;
        while (it.hasNext()) {
            Student s = it.next();
            if (s.total == prevTotal) {
                s.schoolRank = prevRank;
                sameRank++;
            } else {
                s.schoolRank = prevRank == -1 ? 1 : prevRank + 1 + sameRank;// 이전 랭킹 + 동일한 랭킹을 가진 학생 수 + 1 >> 갱신
                prevTotal = s.total;
                prevRank = s.schoolRank;
                sameRank = 0;
            }
        }
    }

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();

        list.add(new Student("이자바", 2, 1, 70, 90, 70));
        list.add(new Student("안자바", 2, 2, 60, 100, 80));
        list.add(new Student("홍길동", 1, 3, 100, 100, 100));
        list.add(new Student("남궁성", 1, 1, 90, 70, 80));
        list.add(new Student("김자바", 1, 2, 80, 80, 90));

        calculateSchoolRank(list);

        Iterator it = list.iterator();

        while (it.hasNext())
            System.out.println(it.next());
    }
}


내가 푼 코드 - 틀림

package com.test.memo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class Student implements Comparable<Student> {

    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;
    int total;
    int schoolRank; // 전교등수
    int classRank; // 반등수

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
        total = kor + eng + math;
    }

    int getTotal() {
        return total;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    public int compareTo(Student o) {
        return this.total - o.total;
    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage()
                + "," + schoolRank + "," + classRank // 새로추가
        ;
    }
}// class Student

class ClassTotalComparator implements Comparator<Student> {

    public int compare(Student o1, Student o2) {
        if (o1.ban != o2.ban) {
            return o2.ban - o1.ban;
        } else
            return o2.total - o1.total;
    }
}

public class Practice {

    static void calculateClassRank(List<Student> list) {
        // 반별 총점 기준 내림차순으로 정렬
        Collections.sort(list, new ClassTotalComparator());

        int prevBan = -1;
        int prevRank = -1;
        int prevTotal = -1;
        int length = list.size();

        Iterator<Student> it = list.iterator();
        int sameRank = 0;

        while (it.hasNext()) {
            Student s = it.next();
            if (s.ban != prevBan) {
                prevBan = s.ban;
                prevTotal = 0;
                sameRank = 0;
            }
            if (s.total == prevTotal) {
                prevRank = s.classRank;
                sameRank++;
            } else {
                s.schoolRank = prevRank == -1 ? 1 : prevRank + sameRank + 1;
                prevTotal = s.total;
                prevRank = s.schoolRank;
                sameRank = 0;
            }
        }
    }

    static void calculateSchoolRank(List<Student> list) {
    }

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList();
        list.add(new Student("이자바", 2, 1, 70, 90, 70));
        list.add(new Student("안자바", 2, 2, 60, 100, 80));
        list.add(new Student("홍길동", 1, 3, 100, 100, 100));
        list.add(new Student("남궁성", 1, 1, 90, 70, 80));
        list.add(new Student("김자바", 1, 2, 80, 80, 90));

        calculateSchoolRank(list);
        calculateClassRank(list);

        Iterator it = list.iterator();

        while (it.hasNext())

            System.out.println(it.next());
    }
}
  • 아 진짜 전혀 모르겠다 으어어 > 왜 자꾸 등수가 저렇게 나오냐고오오
  1. 밑에 선생님 풀이랑 내 Comparator구현하는 클래스의 비교는 맞는거다. 형식만 다를뿐 맞음 그럼왜?

    근데 구조가 달라서 비교하기 힘드니까 그냥 내가 아예 잘못 푼걸로..

선생님 풀이

package com.test.memo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class Student implements Comparable<Student> {
    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;
    int total;
    int schoolRank; // 전교등수
    int classRank; // 반등수

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;

        total = kor + eng + math;
    }

    int getTotal() {
        return total;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    public int compareTo(Student o) {
        return o.total - total;
    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage()
                + "," + schoolRank + "," + classRank // 새로추가
        ;
    }
} // class Student

class ClassTotalComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.ban - o2.ban == 0 ? o2.total - o1.total : o1.ban - o2.ban;
    }
}

class Organize {
    public static void calculateClassRank(List<Student> list) {
        // . 먼저 반별 총점기준 내림차순으로 정렬한다
        Collections.sort(list, new ClassTotalComparator());
        int prevBan = -1;
        int prevRank = -1;
        int prevTotal = -1;
        int length = list.size();

        for (int i = 0, n = 0; i < length; i++, n++) {
            Student s = (Student) list.get(i);

            if (s.ban != prevBan) {
                prevRank = -1;
                prevTotal = -1;
                n = 0;
            }

            if (s.total == prevTotal) {
                s.classRank = prevRank;
            } else {

                s.classRank = n + 1;
            }
            prevBan = s.ban;
            prevRank = s.classRank;
            prevTotal = s.total;
        } // public static void calculateClassRank(List list) {
    }

    public static void calculateSchoolRank(List<Student> list) {
        Collections.sort(list); // 먼저 list를 총점기준 내림차순으로 정렬한다.

        int prevRank = -1; // 이전 전교등수
        int prevTotal = -1; // 이전 총점
        int rank = 1;
        for (Student stu : list) {
            if (stu.getTotal() == prevTotal)
                stu.schoolRank = prevRank;
            else
                stu.schoolRank = rank;
            rank++;
            prevRank = stu.schoolRank;
            prevTotal = stu.getTotal();
        }
    }

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<Student>();
        list.add(new Student("이자바", 2, 1, 70, 90, 70));
        list.add(new Student("안자바", 2, 2, 60, 100, 80));
        list.add(new Student("홍길동", 1, 3, 100, 100, 100));
        list.add(new Student("남궁성", 1, 1, 90, 70, 80));
        list.add(new Student("김자바", 1, 2, 80, 80, 90));
        calculateSchoolRank(list);
        calculateClassRank(list);
        Iterator<Student> it = list.iterator();
        while (it.hasNext())
            System.out.println(it.next());
    }
}


package com.test.memo;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Practice1 {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet();
        int[][] board = new int[5][5];

        for (int i = 0; set.size() < 25; i++) {
            set.add((int) (Math.random() * 30) + 1);
        }

        Iterator<Integer> it = set.iterator();

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = it.next();

                System.out.print((board[i][j] < 10 ? " " : "") + board[i][j] + " ");
            }
            System.out.println();
        }
    }
}
  • HashSet은 중복을 허용하지 않고, 순서를 유지하지 않기 때문에 발생하는 문제다. 아무리 임의의 순서로 저장을 해도, 해싱 알고리즘의 특성상 한 숫자가 고정된 위치에 저장되기 때문이다.

  • 저장 순서를 유지하는 List인터페이스를 구현해 사용하면 된다.

내가 고친 코드

package com.test.memo;

import java.util.ArrayList;
import java.util.Iterator;

public class Practice1 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        int[][] board = new int[5][5];

        for (int i = 0; list.size() < 25; i++) {
            list.add((int) (Math.random() * 30) + 1);
        }

        Iterator<Integer> it = list.iterator();

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = it.next();

                System.out.print((board[i][j] < 10 ? " " : "") + board[i][j] + " ");
            }
            System.out.println();
        }
    }
}


내가 짠 코드 - 정답

package com.test.memo;

import java.util.HashSet;

class SutdaCard {
    int num;
    boolean isKwang;

    SutdaCard() {
        this(1, true);
    }

    SutdaCard(int num, boolean isKwang) {
        this.num = num;
        this.isKwang = isKwang;
    }

    public boolean equals(Object obj) {
        if (obj instanceof SutdaCard) {
            SutdaCard c = (SutdaCard) obj;
            return num == c.num && isKwang == c.isKwang;
        } else {
            return false;
        }
    }

    public String toString() {
        return num + (isKwang ? "K" : "");
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }
}

public class Practice1 {
    public static void main(String[] args) {
        SutdaCard c1 = new SutdaCard(3, true);
        SutdaCard c2 = new SutdaCard(3, true);
        SutdaCard c3 = new SutdaCard(1, true);

        HashSet set = new HashSet();
        set.add(c1);
        set.add(c2);
        set.add(c3);

        System.out.println(set);
    }
}


 12. 다음은 섯다게임에서 카드의 순위를 결정하는 등급목록(족보)이다. HashMap에 등급과 점수를 저장하는 registerJokbo( )와 게임참가자의 점수를 계산해서 반환하는 getPoint( )를 완성하시오. ([참고] 섯다게임은 두 장의 카드의 숫자를 더한 값을 10으로 나눈 나머지가 높은 쪽이 이기는 게임이다. 그 외에도 특정 숫자로 구성된 카드로 이루어진 등급(족보)이 있어서 높은 등급의 카드가 이긴다.)

내가 푼 풀이 - 틀림

왜 값이 문제랑 같게 출력되지 않는거야 ㅠㅠㅠㅠ > 걍 틀린거다. 근데 선생님 풀이도 출력값은 다르게 나오는데 뭐지 - 이유를 알았다 메인 메서드에서 값을 출력할때 띄어쓰기 넣어야 구분이된는데 안넣었어..나 바보냐

package com.test.memo;

import java.util.HashMap;

class SutdaDeck {

    final int CARD_NUM = 20;
    SutdaCard[] cards = new SutdaCard[CARD_NUM];
    int pos = 0;// 다음에 가져올 카드의 위치

    HashMap<String, Integer> jokbo = new HashMap();// 족보를 저장할 HashMap

    SutdaDeck() {
        for (int i = 0; i < cards.length; i++) {
            int num = i % 10 + 1;
            boolean isKwang = i < 10 && (num == 1 || num == 3 || num == 8);
            cards[i] = new SutdaCard(num, isKwang);
        }
        registerJokbo(); // 족보를 등록한다.
    }

    void registerJokbo() {
        jokbo.put("KK", 4000);
        jokbo.put("1010", 3100);
        jokbo.put("99", 3090);
        jokbo.put("88", 3080);
        jokbo.put("77", 3070);
        jokbo.put("66", 3060);
        jokbo.put("55", 3050);
        jokbo.put("44", 3040);
        jokbo.put("33", 3030);
        jokbo.put("22", 3020);
        jokbo.put("11", 3010);
        jokbo.put("12", 2060);
        jokbo.put("21", 2060);
        jokbo.put("14", 2050);
        jokbo.put("41", 2050);
        jokbo.put("19", 2040);
        jokbo.put("91", 2040);
        jokbo.put("110", 2030);
        jokbo.put("101", 2030);
        jokbo.put("104", 2020);
        jokbo.put("410", 2020);
        jokbo.put("46", 2010);
        jokbo.put("64", 2010);
    }

    int getPoint(Player p) {
        if (p == null)
            return 0;
        SutdaCard c1 = p.c1;
        SutdaCard c2 = p.c2;
        Integer result = 0;

        if (c1.isKwang && c2.isKwang) {
            result = jokbo.get("KK");
        } else {
            result = jokbo.get(" " + c1.num + c2.num);
            if (result == null) {
                result = new Integer((c1.num + c2.num) % 10 + 1000);
            }
        }
        p.point = result.intValue();
        /*
         * 
         * (2) 아래의 로직에 맞게 코드를 작성하시오 .
         * 
         * 1. 카드 두 장이 모두 광이면, jokbo에서 키를 "KK"로 해서 점수를 조회한다.
         * 
         * 2. 두 카드의 숫자(num)로 jokbo에서 등급을 조회한다.
         * 
         * 3. 해당하는 등급이 없으면, 아래의 공식으로 점수를 계산한다.
         * 
         * (c1.num+c2.num)%10+1000
         * 
         * 4. Player의 점수(point)에 계산한 값을 저장한다.
         * 
         */
        return result.intValue();
    }

    SutdaCard pick() throws Exception {
        SutdaCard c = null;

        if (0 <= pos && pos < CARD_NUM) {
            c = cards[pos];
            cards[pos++] = null;
        } else {
            throw new Exception("남아있는 카드가 없습니다.");
        }
        return c;
    }

    void shuffle() {
        for (int x = 0; x < CARD_NUM * 2; x++) {
            int i = (int) (Math.random() * CARD_NUM);
            int j = (int) (Math.random() * CARD_NUM);

            SutdaCard tmp = cards[i];
            cards[i] = cards[j];
            cards[j] = tmp;
        }
    }
}// SutdaDeck

class Player {
    String name;
    SutdaCard c1;
    SutdaCard c2;

    int point;// 카드의 등급에 따른 점수 - 새로 추가

    Player(String name, SutdaCard c1, SutdaCard c2) {
        this.name = name;
        this.c1 = c1;
        this.c2 = c2;
    }

    public String toString() {
        return "[" + name + "]" + c1.toString() + "," + c2.toString();
    }
}// class Player

class SutdaCard {
    int num;
    boolean isKwang;

    SutdaCard() {
        this(1, true);
    }

    SutdaCard(int num, boolean isKwang) {
        this.num = num;
        this.isKwang = isKwang;
    }

    public String toString() {
        return num + (isKwang ? "K" : "");
    }
}

public class Practice1 {
    public static void main(String[] args) throws Exception {
        SutdaDeck deck = new SutdaDeck();

        deck.shuffle();

        Player p1 = new Player("타짜", deck.pick(), deck.pick());
        Player p2 = new Player("고수", deck.pick(), deck.pick());

        System.out.println(p1 + "" + deck.getPoint(p1));
        System.out.println(p2 + "" + deck.getPoint(p2));
    }
}

정답

package com.test.memo;

import java.util.HashMap;

class SutdaDeck {

    final int CARD_NUM = 20;
    SutdaCard[] cards = new SutdaCard[CARD_NUM];
    int pos = 0;// 다음에 가져올 카드의 위치

    HashMap<String, Integer> jokbo = new HashMap<>();// 족보를 저장할 HashMap

    SutdaDeck() {
        for (int i = 0; i < cards.length; i++) {
            int num = i % 10 + 1;
            boolean isKwang = i < 10 && (num == 1 || num == 3 || num == 8);
            cards[i] = new SutdaCard(num, isKwang);
        }
        registerJokbo(); // 족보를 등록한다.
    }

    void registerJokbo() {
        jokbo.put("KK", 4000);
        jokbo.put("1010", 3100);
        jokbo.put("99", 3090);
        jokbo.put("88", 3080);
        jokbo.put("77", 3070);
        jokbo.put("66", 3060);
        jokbo.put("55", 3050);
        jokbo.put("44", 3040);
        jokbo.put("33", 3030);
        jokbo.put("22", 3020);
        jokbo.put("11", 3010);

        jokbo.put("12", 2060);
        jokbo.put("21", 2060);
        jokbo.put("14", 2050);
        jokbo.put("41", 2050);
        jokbo.put("19", 2040);
        jokbo.put("91", 2040);
        jokbo.put("110", 2030);
        jokbo.put("101", 2030);
        jokbo.put("104", 2020);
        jokbo.put("410", 2020);
        jokbo.put("46", 2010);
        jokbo.put("64", 2010);
    }

    int getPoint(Player p) {
        if (p == null)
            return 0;

        SutdaCard c1 = p.c1;
        SutdaCard c2 = p.c2;

        Integer result = 0;
        String tmp = "";

        if (c1.isKwang == true && c2.isKwang == true)
            tmp = "KK";
        else
            tmp = "" + c1.num + c2.num;
        result = jokbo.get(tmp);
        if (result == null)
            result = (c1.num + c2.num) % 10 + 1000;
        p.point = result.intValue();
        p.point = result.intValue();
        /*
         * 
         * (2) 아래의 로직에 맞게 코드를 작성하시오 .
         * 
         * 1. 카드 두 장이 모두 광이면, jokbo에서 키를 "KK"로 해서 점수를 조회한다.
         * 
         * 2. 두 카드의 숫자(num)로 jokbo에서 등급을 조회한다.
         * 
         * 3. 해당하는 등급이 없으면, 아래의 공식으로 점수를 계산한다.
         * 
         * (c1.num+c2.num)%10+1000
         * 
         * 4. Player의 점수(point)에 계산한 값을 저장한다.
         * 
         */
        return result.intValue();
    }

    SutdaCard pick() throws Exception {
        SutdaCard c = null;

        if (0 <= pos && pos < CARD_NUM) {
            c = cards[pos];
            cards[pos++] = null;
        } else {
            throw new Exception("남아있는 카드가 없습니다.");
        }
        return c;
    }

    void shuffle() {
        for (int x = 0; x < CARD_NUM * 2; x++) {
            int i = (int) (Math.random() * CARD_NUM);
            int j = (int) (Math.random() * CARD_NUM);

            SutdaCard tmp = cards[i];
            cards[i] = cards[j];
            cards[j] = tmp;
        }
    }
}// SutdaDeck

class Player {
    String name;
    SutdaCard c1;
    SutdaCard c2;

    int point;// 카드의 등급에 따른 점수 - 새로 추가

    Player(String name, SutdaCard c1, SutdaCard c2) {
        this.name = name;
        this.c1 = c1;
        this.c2 = c2;
    }

    public String toString() {
        return "[" + name + "]" + c1.toString() + "," + c2.toString();
    }
}// class Player

class SutdaCard {
    int num;
    boolean isKwang;

    SutdaCard() {
        this(1, true);
    }

    SutdaCard(int num, boolean isKwang) {
        this.num = num;
        this.isKwang = isKwang;
    }

    public String toString() {
        return num + (isKwang ? "K" : "");
    }
}

public class Practice1 {
    public static void main(String[] args) throws Exception {
        SutdaDeck deck = new SutdaDeck();

        deck.shuffle();

        Player p1 = new Player("타짜", deck.pick(), deck.pick());
        Player p2 = new Player("고수", deck.pick(), deck.pick());

        System.out.println(p1 + " " + deck.getPoint(p1));
        System.out.println(p2 + " " + deck.getPoint(p2));
    }
}


package com.test.memo;

import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

class Player{
    String name;
    SutdaCard c1;
    SutdaCard c2;

    int point; //카드의 등급에 따른 점수 

    Player(String name, SutdaCard c1, SutdaCard c2) {
        this.name = name;
        this.c1 = c1;
        this.c2 = c2;
    }

    @Override
    public String toString() {
        return "[" + name + "]" + c1.toString() + "," + c2.toString();
    }
}
class SutdaCard{
    int num;
    boolean isKwang;

    SutdaCard() {
        this(1, true);
    }
    SutdaCard(int num, boolean isKwang) {
        this.num = num;
        this.isKwang = isKwang;
    }
    @Override
    public String toString() {
        return num + (isKwang ? "K" : "");
    }
}
class SutdaDeck{
    SutdaCard[] cards = new SutdaCard[20];
    int pos = 0; //다음에 가져올 카드 위치

    HashMap<String, Integer> jokbo = new HashMap<>();

    SutdaDeck() {
        for(int i = 0; i < cards.length; i++) {
            int num = i % 10 + 1;
            boolean isKwang = i < 10 && (num == 1 || num == 3 || num == 8);
            cards[i] = new SutdaCard(num, isKwang);
        }
        registerJokbo();
    }
    void registerJokbo() {
        jokbo.put("KK", 4000);
        jokbo.put("1010",3100); jokbo.put("12", 2060);
        jokbo.put("99", 3090); jokbo.put("21", 2060);
        jokbo.put("88", 3080); jokbo.put("14", 2050);
        jokbo.put("77", 3070); jokbo.put("41", 2050);
        jokbo.put("66", 3060); jokbo.put("19", 2040);
        jokbo.put("55", 3050); jokbo.put("91", 2040);
        jokbo.put("44", 3040); jokbo.put("110", 2030);
        jokbo.put("33", 3030); jokbo.put("101", 2030);
        jokbo.put("22", 3020); jokbo.put("104", 2020);
        jokbo.put("11", 3010); jokbo.put("410", 2020);
        jokbo.put("46", 2010);
        jokbo.put("64", 2010);
    }
    void shuffle() {
        for(int i = 0; i < cards.length; i++) {
            int j = (int)(Math.random()* cards.length);
            SutdaCard tmp = cards[i];
            cards[i] = cards[j];
            cards[j] = tmp;
        }
    }
    int getPoint(Player p) {
        if(p == null) return 0;
        SutdaCard c1 = p.c1;
        SutdaCard c2 = p.c2;
        Integer result = 0;
        if(c1.isKwang && c2.isKwang) {
            result = jokbo.get("KK");
        }else {
            result = jokbo.get("" + c1.num + c2.num);
            if(result == null) {
                result = (c1.num + c2.num) % 10 + 1000;
            }
        }
        p.point = result.intValue();//객체를 정수형으로 저장(int) 
        return result.intValue();
    }
    SutdaCard pick() throws Exception {
        SutdaCard c = null;
        if(0 <= pos && pos < cards.length) {
            c = cards[pos];
            cards[pos++] = null;
        }else {
            throw new Exception("남아있는 카드가 없습니다.");
        }
        return c;
    }

}
public class Organize {

    public static void main(String[] args) throws Exception {
        SutdaDeck deck = new SutdaDeck();
        deck.shuffle();
        Player[] pArr = { 
                new Player("타짜", deck.pick(), deck.pick()), 
                new Player("고수", deck.pick(), deck.pick()),
                new Player("물주", deck.pick(), deck.pick()),
                new Player("중수", deck.pick(), deck.pick()),
                new Player("하수", deck.pick(), deck.pick()) };

        TreeMap<Player, Integer> rank = new TreeMap<>(new Comparator<Player>() {

            @Override
            public int compare(Player o1, Player o2) {
                return o2.point - o1.point;
            }
        });
        for(int i = 0; i < pArr.length; i++) {
            Player p = pArr[i];
            rank.put(p, deck.getPoint(p));
            System.out.println(p + " " + deck.getPoint(p));
        }
        System.out.println();
        System.out.println("1위는 " + rank.firstKey() + "입니다.");
    }
}


업로드중..

package com.test.memo;

import java.util.ArrayList;
import java.util.Scanner;

class Practice {
    static ArrayList<Student> record = new ArrayList<Student>(); // 성적데이터를 저장할 공간
    static Scanner s = new Scanner(System.in);

    public static void main(String args[]) {
        while (true) {
            switch (displayMenu()) {
            case 1:
                inputRecord();
                break;
            case 2:
                displayRecord();
                break;
            case 3:
                System.out.println("프로그램을 종료합니다.");
                System.exit(0);
            }
        } // while(true)
    }

    // menu를 보여주는 메서드
    static int displayMenu() {
        System.out.println("**************************************************");
        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.print("원하는 메뉴를 선택하세요.(1~3) : ");
        int menu = 0;

        while (true) {
            menu = Integer.parseInt(s.nextLine());
            if (menu >= 1 && menu <= 3)
                break;
            System.out.println("메뉴를 잘못 선택하셨습니다. 다시 입력해주세요.");
            System.out.print("원하는 메뉴를 선택하세요.(1~3) : ");
        }
        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(">>");
            String str = s.nextLine();
            if (str.equalsIgnoreCase("q"))
                break;
            String[] strArr = str.split(",");
            try {
                if (record.add(new Student(strArr[0], Integer.parseInt(strArr[1]), Integer.parseInt(strArr[2]),
                        Integer.parseInt(strArr[3]), Integer.parseInt(strArr[4]), Integer.parseInt(strArr[5]))))
                    break;
            } catch (Exception e) {
                System.out.println("입력오류입니다 이름, 반, 번호, 국어성적, 영어성적, 수학성적' 의 순서로 입력하세요.");
            }

        } // end of while
    } // public static void inputRecord() {
        // 데이터 목록을 보여주는 메서드

    static void displayRecord() {
        int koreanTotal = 0;
        int englishTotal = 0;
        int mathTotal = 0;
        int total = 0;
        int length = record.size();
        if (length > 0) {
            System.out.println();
            System.out.println("이름 반 번호 국어 영어 수학 총점 평균 전교등수 반등수");
            System.out.println("====================================================");
            for (int i = 0; i < length; i++) {
                Student student = record.get(i);
                System.out.println(student);
                koreanTotal += student.kor;
                mathTotal += student.math;
                englishTotal += student.eng;
                total += student.total;
            }
            System.out.println("====================================================");
            System.out.println("총점 : " + koreanTotal + " " + englishTotal + " " + mathTotal + " " + total);
            System.out.println();
        } else {
            System.out.println("====================================================");
            System.out.println("데이터가 없습니다.");
            System.out.println("====================================================");
        }
    } // static void displayRecord() {
}

class Student implements Comparable<Student> {
    String name;
    int ban;
    int no;
    int kor;
    int eng;
    int math;
    int total;
    int schoolRank;
    int classRank; // 반등수

    Student(String name, int ban, int no, int kor, int eng, int math) {
        this.name = name;
        this.ban = ban;
        this.no = no;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
        total = kor + eng + math;
    }

    int getTotal() {
        return total;
    }

    float getAverage() {
        return (int) ((getTotal() / 3f) * 10 + 0.5) / 10f;
    }

    @Override
    public int compareTo(Student o) {
        return o.total - total;
    }

    public String toString() {
        return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage()
                + "," + schoolRank + "," + classRank;
    }
} // class Studentj

0개의 댓글