IT/Programming / / 2023. 4. 21. 17:38

[JAVA] getter, setter, this 사용 예제

반응형
package dayday9;

import javax.swing.JOptionPane;

class student{
	String name;
	int point;
	char grade;
	
	protected String getName() {
		return name;
	}
	protected void setName(String name) {
		this.name = name;
	}
	protected int getPoint() {
		return point;
	}
	protected void setPoint(int point) {
		this.point = point;
	}
	protected char getGrade() {
		return grade;
	}
	protected void setGrade(char grade) {
		this.grade = grade;
	}
	void setInfo(String n, int p){
		name = n;
		if(p < 0) point = 0;
		else if(p > 100) point = 100;
		else point = p;//예외 변수 처리
		setGrade();
	}
	//this  : 이 해당 객체의 인스턴스변수를 할당받을때 사용
	//this. 
	void setGrade(){
		if(point >= 90){
			this.grade = 'A';
		}else if(point >= 80){
			this.grade = 'B';
		}else if(point >= 70){
			this.grade = 'B';
		}else if(point >= 60){
			this.grade = 'B';
		}else grade = 'F';
	}
	
	String showAll(){
		return "이름 : " +this.name + "성적 : " + point + " 점 " + "성적 : " + grade;
	}
	
	boolean pass(){
		return point >= 60 ? true : false;
	}
}
public class test00 {
	public static void main(String[] args) {
		student st= null;
		String mess = "1. 등록 \n 2. 보기\n 3. 합격확인\n4. 종료";
		String select = "";
		while(true){
			select = JOptionPane.showInputDialog(mess);
			if(select.equals("1")){
				st = new student();
				String name = JOptionPane.showInputDialog("이름");
				String sPoint = JOptionPane.showInputDialog("점수");
				int point = Integer.parseInt(sPoint);
				st.setInfo(name, point);
				
			}else if(select.equals("2")){
				if(st == null){
					JOptionPane.showMessageDialog(null, "등록된 학생이 없습니다. 학생을 등록하세요");
				}else JOptionPane.showMessageDialog(null,st.showAll());
				
			}else if(select.equals("3")){
				if(st == null){
					JOptionPane.showMessageDialog(null, "등록된 학생이 없습니다. 학생을 등록하세요");
				}else{
					String mess2 = st.pass() ? "합격" : "불합격";
					JOptionPane.showMessageDialog(null, mess2);
				}
				
			}else if(select.equals("4")){
				JOptionPane.showMessageDialog(null, "프로그램을 종료합니다.");
				break;
				
			}else 

				JOptionPane.showMessageDialog(null, "잘못 입력하셨습니다. 프로그램을 종료합니다.");
			break;
		}
	
	}
}
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유