JAVA/chapter11_reference_array
chapter03 : Student / StudentMain / StudentManager
GAWON
2023. 5. 26. 18:20
package org.joonzis.ex;
public class Ex03_Student {
String name, dept, score1, score2;
double average;
boolean isPass;
public Ex03_Student() {}
public Ex03_Student(String name, String dept, String score1, String score2) {
this.name = name;
this.dept = dept;
this.score1 = score1;
this.score2 = score2;
this.average = getAverage();
this.isPass = getPass();
}
double getAverage() {
return (Double.parseDouble(score1) + Double.parseDouble(score2)) / 2.0;
}
boolean getPass() {
return average >= 80 ? true : false;
}
void output() {
System.out.println("이름 : " + name);
System.out.println("학과 : " + dept);
System.out.println("평균 점수 : " + average);
System.out.println("합격유무 : " + (isPass ? "합격" : "불합격"));
}
}
package org.joonzis.ex;
public class Ex03_StudentMain {
public static void main(String[] args) {
// manager를 이용하여 학생 추가
Ex03_StudentManager manager = new Ex03_StudentManager(2);
manager.addNewStudent(manager.input());
manager.addNewStudent(manager.input());
// 전체 학생의 정보 출력
manager.outputAllStudents();
// 전체 평균 출력
manager.outputAverage();
// 특정 학생 찾아서 정보 출력
// 학생을 찾아서 리턴 메소드
// 전달 받은 학생의 정보를 출력하는 메소드
manager.output(manager.findStudent());
}
}
package org.joonzis.ex;
import java.util.Scanner;
public class Ex03_StudentManager {
int idx; // 외부(전역)에서 접근 가능한 인덱스
Ex03_Student[] arr;
Scanner sc = new Scanner(System.in);
// 생성자 - 몇 명의 학생을 관리할지 - 배열 선언
public Ex03_StudentManager() {}
public Ex03_StudentManager(int numOfStudents) {
arr = new Ex03_Student[numOfStudents];
}
// 학생 정보를 저장한 뒤 학생 객체 리턴
Ex03_Student input() {
System.out.print("학생 이름 >> ");
String name = sc.nextLine();
System.out.print("학생 학과 >> ");
String dept = sc.nextLine();
System.out.print("중간 점수 >> ");
String score1 = sc.nextLine();
System.out.print("기말 점수 >> ");
String score2 = sc.nextLine();
return new Ex03_Student(name, dept, score1, score2);
}
// input() 에서 받아온 학생 객체를 배열에 저장
void addNewStudent(Ex03_Student student) {
arr[idx] = student;
idx++;
}
// 전체 학생 정보 출력
void outputAllStudents() {
for(int i=0; i<idx; i++) {
System.out.println((i+1) + "번 학생 정보------");
arr[i].output();
}
}
// 학생 전체의 평균 점수 출력
void outputAverage() {
double total = 0;
for(int i=0; i<idx; i++) {
total += arr[i].getAverage();
}
System.out.println("***** 전체 평균 : " + (total / idx));
}
// 학생 찾는 메소드
Ex03_Student findStudent() {
System.out.print("찾을 학생의 이름 입력 >> ");
String name = sc.next();
for(int i=0; i<idx; i++) {
if(name.equals(arr[i].name)) {
return arr[i];
}
}
return null; // 찾는 학생이 없을 때
}
// 학생 정보를 전달 받아 출력하는 메소드
void output(Ex03_Student student) {
if(student != null) {
student.output();
}else {
System.out.println("찾는 학생이 없습니다.");
}
}
}