[JAVA] Day 8 - class로부터 객체 생성 [석차 구하기]

sue·2023년 11월 23일

📒국비학원 [JAVA]

목록 보기
5/20
post-thumbnail

클래스(class)

  • 객체를 만들기 위한 틀 → (객체 = instance)

🔎 [Eclipse] - [package] - [class] 생성


📌 Note Code



Test1. 이름과 3과목의 성적,총합,평균,석차를 구하여라

💻 입력-1 파일명 : [ Score ] - main메소드 x

import java.util.Scanner;

public class Score {

	// class = 자료형
	
	/*
	 	int[] a; // a는 int 배열에 정수값 여러개 저장가능 int a; //a는 int값 3개 저장할 수 있음. Record b;
	 	b는 class인 Record - 7개 데이터 저장할 수 있음. => *class = 자료형
	 */

	int inwon;
	Record[] rec;

	Scanner sc = new Scanner(System.in);

	public void set() {

		do {
			System.out.print("인원수?");// 3
			inwon = sc.nextInt();
		} while (inwon < 1 || inwon > 10);

		// 배열의 객체 생성
		rec = new Record[inwon]; // 인원수만큼! - class의 초기값 null

	}

	public void input() {

		String[] title = { "국어?", "영어?", "수학?" };

		// Scanner sc = new Scanner(System.in); //위에 있는데 또 써아하는가? -> 복도로 뺌
		// 아래 이름~ 평균 => rec[0]번지에 다 들어가있음

		// new Record(); = heap공간

		for (int i = 0; i < inwon; i++) {

			rec[i] = new Record();// 레코드를 복사한 new Record(); 이게 가지고 있는 주소번지에
			// 레코드 값을 넣는다! 그래서 이름 input하기전에
			// rec복사한 몇번지 = 레코드 복사한 주소번지에new Record(); 값을 넣고
			// 이름을 물어본다

			System.out.print((i + 1) + "번째 이름은?");
			rec[i].name = sc.next();

			for (int j = 0; j < 3; j++) {// j = {국 영 수} 번지수

				System.out.print(title[j]);
				rec[i].score[j] = sc.nextInt();

				// 누적 +=
				rec[i].tot += rec[i].score[j];// 총점
			}

			rec[i].ave = rec[i].tot / 3;

		}

	}

	// private = 내부적으로 실행이 가능해서 보완문제
	private void ranking() { // 외부에선 접근할 수 없는, 직원 only

		int i, j; // 지역변수 : 내부에서만 사용하는 변수

		// 석차 초기화
		for (i = 0; i < inwon; i++) {
			rec[i].rank = 1;
		}

		// 석차 구하기
		// selection sort

		for (i = 0; i < inwon - 1; i++) {
			for (j = i + 1; j < inwon; j++) {

				if (rec[i].tot > rec[j].tot) {
					rec[j].rank++; // 작은쪽에 ++
				} else if (rec[i].tot < rec[j].tot) // else를 못쓰는 이유? 동점일때 랜덤으로 등수 매김
					rec[i].rank++;
			}
		}

	}

	public void print() {

		ranking(); //private : 스탭끼리는 왔다갔다 가능하므로 ranking 메소드 호출

		for (int i = 0; i < inwon; i++) {
			System.out.printf("%6s", rec[i].name);

			for (int j = 0; j < 3; j++) {
				System.out.printf("%6d", rec[i].score[j]);
			}

			System.out.printf("%6d", rec[i].tot);
			System.out.printf("%6d", rec[i].ave);
			System.out.printf("%6d\n", rec[i].rank);
		}
	}

}

/*
	System.out.print("국어?"); rec[i].score[0] = sc.nextInt();

	System.out.print("영어?"); rec[i].score[1] = sc.nextInt();

	System.out.print("수학?"); rec[i].score[2] = sc.nextInt();
 */


💡 **출력**
main 출입문이 없기때문에 출력이 나올 수 없다

0개의 댓글