개발 공부/JAVA

[JAVA] 성적 출력 프로그램 MVC로 구현해보기

sngynhy 2021. 7. 21. 19:51

학생들의 점수를 입력받아 평균/학점을 출력

 

[Model 코드]

public class StudentModel {

	private String name;
	private int korean;
	private int math;
	private int english;
	private String grade;

	public StudentModel(String name, int korean, int math, int english) {
		this.name = name;
		this.korean = korean;
		this.math = math;
		this.english = english;
		grade();
	}

	private void grade() {
		int avg = avg();
		if (avg >= 80) {
			this.grade = "A";
		} else if (avg >= 50) {
			this.grade = "B";
		} else {
			this.grade = "C";
		}
	}

	public int avg() {
		return (this.korean + this.math + this.english) / 3;
	}

	public String getGrade() {
		return this.grade;
	}
}

 

[View 코드]

import java.util.InputMismatchException;
import java.util.Scanner;

public class StudentView {

	Scanner sc;
	public String name;
	public int korean;
	public int math;
	public int english;

	public StudentView() {
		sc = new Scanner(System.in);
	}

	public boolean scoreInput() {
		try {
			if (this.name == null ) {
				System.out.print("학생 이름: ");
				this.name = sc.next();
			}
			if (this.korean == 0) {
				System.out.print("국어 점수: ");
				this.korean = sc.nextInt();
			}
			if (this.math == 0) {
				System.out.print("수학 점수: ");
				this.math = sc.nextInt();
			}
			if (this.english == 0) {
				System.out.print("영어 점수: ");
				this.english = sc.nextInt();
			}
		} catch (InputMismatchException e) {
			sc.nextLine();
			System.out.println("올바르지 않은 입력입니다!");
			return false;
		}
		return true;
		
	}
	
	public void showGrade(int avg, String grade) {
		System.out.println(this.name + " 학생의 평균 " + avg + "점 학점 [" + grade + "]");
	}
}

 

[Controller 코드]

import model.StudentModel;
import view.StudentView;


public class StudentController {

	StudentView view;
	StudentModel model;

	public StudentController() {
		view = new StudentView();
		getGrade();
	}

	public void getGrade() {
		while (true) {
			boolean inputSuccess = view.scoreInput();
			if (!inputSuccess) {  // 성공적으로 Input값을 받지 못했을 때
				continue;
			}
			// V -> M
			model = new StudentModel(view.name, view.korean, view.math, view.english);
			// M -> V
			view.showGrade(model.avg(), model.getGrade());
			break;
		}
	}

}

 

[main함수 코드]

import controller.StudentController;

public class StudentTest {

	public static void main(String[] args) {

		new StudentController();

	}

}