[Student] Lombok 적용(@Getter, @Setter)

2022. 1. 30. 12:39·◈ Human Project/Custom : Student🏫
728x90


 

[Student] Exception 적용(RangeException, NumberFormatException)

로 배열 수정" data-og-description="1. interface 분리 package service; public interface StudentService { void list(); void register(); void modify(); void remove(); } 2. ArrayList<>로 배열 수정 -..

yermi.tistory.com


1. class Student에 Lombok 적용하기

 

[꿀팁] Eclipse에 롬복(Lombok) 연동하기[코드 축약 라이브러리, Lombok]

1. Lombok 다운로드 및 설치 Project Lombok projectlombok.org 2. Eclipse에 Lombok 연동하기 3. Lombok 사용하기 - Lombok 어노테이션 @Getter and @Setter @NonNull @ToString @EqualsAndHashCode @Data @Cl..

yermi.tistory.com

 

Student class에 Lombok 적용 / @Getter, @Setter


- app : class StudentEx

package app;

import service.StudentService;
import service.StudentServiceImpl;
import utils.StudentUtil;

public class StudentEx {  
	public static void main(String[] args) {
		StudentService service = new StudentServiceImpl();
		// 1. 목록 조회 2. 학생 등록 3. 학생 정보 수정 4. 학생 삭제 5. 종료

		for (boolean b = true ; b ;) {	
			try {
			
				int input = StudentUtil.nextInt("1. 목록 조회 2. 학생 등록 3. 학생 정보 수정 4. 학생 삭제 5. 종료\n", 1, 5);
				
				switch (input) {
				case 1:
					System.out.println("목록 조회입니다.");
					service.list();
					break;
					
				case 2:
					System.out.println("학생 등록입니다.");
					service.register();
					break;
					
				case 3:
					System.out.println("학생 정보 수정입니다.");
					service.modify();
					break;
					
				case 4:
					System.out.println("학생 삭제입니다.");
					service.remove();
					break;
					
				case 5:
					System.out.println("종료합니다.");
					b = false;
					break;
					
				default:
					System.out.println("올바른 번호를 입력하세요.");
					break;
				}
			} catch (NumberFormatException e) {
				System.out.println("숫자 형식으로 입력해주세요.");
			} catch (RuntimeException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}

- domain : class Student

package domain;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter

public class Student {

	// 필드 : 학번, 이름, 국어, 영어, 수학	
	private String no;
	private String name;
	private int kor;
	private int eng;
	private int mat;
	
	// 생성자
	public Student() {
		// TODO Auto-generated constructor stub
	}
	
	public Student(String no, String name) {
		this(no, name, getScore(), getScore(), getScore());
	}

	public Student(String no, String name, int kor, int eng, int mat) {
		super();
		this.no = no;
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.mat = mat;
	}

	// 총점, 평균
	public int sum () {
		return kor + eng + mat;
	}
	
	public double avg () {
		return (int)(sum() / 3d * 100) / 100d;
	}
	
//	점수 랜덤
	private static int getScore() {
		return (int) (Math.random() * 41) + 60; // 국어, 영어, 수학 점수 랜덤 출력
	}

//	toString 정의
	public String toString() {
		return String.format(" %5s%5s \t %3d \t %3d \t %3d \t %3d \t %2.2f",
							no, name, kor, eng, mat, sum(), avg());
	}
}

- service : interface StudentService

package service;

public interface StudentService {
	void list();
	
	void register();
	
	void modify();
	
	void remove();
}

- service : class StudentServiceImpl

package service;

import static utils.StudentUtil.*;

import java.util.ArrayList;
import java.util.List;

import domain.Student;

// 기능 담당
public class StudentServiceImpl implements StudentService {
	List<Student> students = new ArrayList<Student>();
	
	{
		String[] names = { "김경보", "김동엽", "김상현", "김승종", "김예찬", "김경보", "김태윤" };

		for (int i = 0; i < names.length; i++) {
				students.add(new Student(22000 + i + 1 + "", names[i]));
		}
		System.out.println("임시 데이터 초기화 완료");
	}

	// 1. 조회하기
	public void list() { // 조회 기능 구현
		System.out.println("조회 기능 구현");
		System.out.printf(" 학번 \t 이름 \t 국어 \t 영어 \t 수학 \t 총점 \t 평균 %n");
		System.out.printf("======================================================%n");

		for (int i = 0; i < students.size(); i++) {
			System.out.println(students.get(i));
		}
	}
	// 2. 등록하기
	public void register() { // 등록 기능 구현
		System.out.println("등록 기능 구현");

		students.add(new Student(nextLine("학번 >"), nextLine("이름 >", true),
								nextInt("국어 >"), nextInt("영어 >"), nextInt("수학 >")));
		
		System.out.println("정상 등록 되었습니다.");
	}
	// 3. 수정하기
	public void modify() { // 수정 기능 구현
		System.out.println("수정 기능 구현");
		
		// 학번으로 학생을 탐색 후 학생 데이터 중 이름, 국어, 영어, 수학점수를 수정
		Student student = findBy(nextLine("수정할 학생의 학번 >"));
		if (student == null) {
			System.out.println("존재하지 않는 학번입니다");
			return;
		}
		student.setName(nextLine("이름 >", true));
		
		student.setKor(nextInt("국어 >"));
		student.setEng(nextInt("영어 >"));
		student.setMat(nextInt("수학 >"));
	}
	// 4. 삭제하기
	public void remove() {
		System.out.println("삭제 기능 구현");
		students.remove(findIndexBy(nextLine("삭제할 학생의 학번 >")));
		System.out.println("삭제 완료 되었습니다.");
	
	}
	private Student findBy (String no) {
		Student student = null;
		for (Student s : students) {
			if (s.getNo().equals(no)) {
				student = s;
			}
		}
		return student;
	}
	
	private int findIndexBy (String no) {
		int ret = -1;
		for (int i = 0; i < students.size(); i++) {	
			if (students.get(i).getNo().equals(no)) {
				ret = i;
				break;
			}
		}
		return ret;
	}
}

- exception : class RangeException

package exception;

public class RangeException extends RuntimeException {

	private int start;
	private int end;
	
	public RangeException() {
	}

	public RangeException(int start, int end) {
		super(String.format("값의 범위를 %d ~ %d로 지정하세요.", start, end));
		this.start = start;
		this.end = end;
	}
}

- utils : StudentUtil

package utils;

import java.util.Scanner;

import exception.RangeException;

public class StudentUtil {
	private static Scanner scanner = new Scanner(System.in);
	
	public static String nextLine(String input) {
		return nextLine(input, false);
	}
	
	public static String nextLine(String input, boolean korean) {
		System.out.print(input);
		String str = scanner.nextLine();
		if (korean) {
			for (int i = 0 ; i < str.length() ; i++) {
				if (str.charAt(i) < '가' || str.charAt(i) > '힣') {
					throw new RuntimeException("한글로 입력해주세요.");
				}
			}
		}
		return str;
	}
	
	public static int nextInt(String input) {
		return nextInt(input, 0, 100);
	}
	
	public static int nextInt(String input, int start, int end) {
		int result = Integer.parseInt(nextLine(input));
		if (start > result || end < result)
			throw new RangeException(start, end);
		return result;
	}
}

 

 

[Student] String.format을 이용한 출력 양식 정리

[Student] Lombok 적용(@Getter, @Setter) 로 배열 수정 -.." data-og-host="yermi.tistory.com" data-og-source-url="https://yermi.tistory.com/85" data-og-url="https://yermi.tistory.com/85" data-og-ima..

yermi.tistory.com

728x90
'◈ Human Project/Custom : Student🏫' 카테고리의 다른 글
  • [Student] 직렬화를 사용한 데이터 영속화
  • [Student] String.format을 이용한 출력 양식 정리
  • [Student] Exception 적용(RangeException, NumberFormatException)
  • [Student] interface 분리, ArrayList<>로 배열 수정
예르미(yermi)
예르미(yermi)
끊임없이 제 자신을 계발하는 개발자입니다👨🏻‍💻
  • 예르미(yermi)
    예르미의 코딩노트
    예르미(yermi)
  • 전체
    오늘
    어제
    • 분류 전체보기 (937)
      • ◎ Java (133)
        • Java☕ (93)
        • JSP📋 (26)
        • Applet🧳 (6)
        • Interview👨🏻‍🏫 (8)
      • ◎ JavaScript (48)
        • JavaScript🦎 (25)
        • jQuery🌊 (8)
        • React🌐 (2)
        • Vue.js🔰 (6)
        • Node.js🫒 (3)
        • Google App Script🐑 (4)
      • ◎ HTML5+CSS3 (17)
        • HTML5📝 (8)
        • CSS3🎨 (9)
      • ──────────── (0)
      • ▣ Framework (67)
        • Spring🍃 (36)
        • Spring Boot🍀 (12)
        • Bootstrap💜 (3)
        • Selenium🌕 (6)
        • MyBatis🐣 (10)
      • ▣ Tools (47)
        • API🎯 (18)
        • Library🎲 (15)
        • JitPack🚀 (3)
        • Jenkins👨🏻 (7)
        • Thymeleaf🌿 (4)
      • ▣ Server (32)
        • Apache Tomcat🐱 (14)
        • Apache HTTP Server🛡️ (1)
        • Nginx🧶 (7)
        • OracleXE💿 (4)
        • VisualSVN📡 (4)
      • ▣ OS : 운영체제 (18)
        • cmd : 명령프롬프트💻 (10)
        • Linux🐧 (8)
      • ▣ SQL : Database (56)
        • Oracle SQL🏮 (26)
        • PL SQL💾 (9)
        • MySQL🐬 (6)
        • MariaDB🦦 (6)
        • H2 Database🔠 (3)
        • SQL 실전문제🐌 (6)
      • ────────── (0)
      • ◈ Human Project (86)
        • Mini : Library Service📚 (15)
        • 화면 설계 [HTML]🐯 (10)
        • 서버 프로그램 구현🦁 (15)
        • Team : 여수어때🛫 (19)
        • Custom : Student🏫 (9)
        • Custom : Board📖 (18)
      • ◈ Yermi Project (40)
        • 조사모아(Josa-moa)📬 (5)
        • Riddle-Game🧩 (6)
        • 맛있을 지도🍚 (2)
        • 어디 가! 박대리!🙋🏻‍♂️ (5)
        • 조크베어🐻‍❄️ (4)
        • Looks Like Thirty🦉 (2)
        • Toy Project💎 (12)
        • 오픈소스 파헤치기🪐 (4)
      • ◈ Refactoring (15)
        • Mini : Library Service📚 (8)
        • 서버 프로그램 구현🦁 (1)
        • Team : 여수어때🛫 (0)
        • 쿼리 튜닝일지🔧 (6)
      • ◈ Coding Test (89)
        • 백준(BOJ)👨🏻‍💻 (70)
        • 프로그래머스😎 (2)
        • 코드트리🌳 (7)
        • 알고리즘(Algorithm)🎡 (10)
      • ◈ Study (102)
        • 기초튼튼 개발지식🥔 (25)
        • HTTP 웹 지식💡 (4)
        • 클린코드(Clean Code)🩺 (1)
        • 디자인패턴(GoF)🥞 (12)
        • 다이어그램(Diagram)📈 (4)
        • 파이썬(Python)🐍 (16)
        • 에러노트(Error Note)🧱 (34)
        • 웹 보안(Web Security)🔐 (6)
      • ◈ 공부모임 (39)
        • 혼공학습단⏰ (18)
        • 코드트리 챌린지👊🏻 (2)
        • 개발도서 100독👟 (8)
        • 나는 리뷰어다🌾 (11)
      • ◈ 자격증 공부 (37)
        • 정보처리기사🔱 (16)
        • 정보처리산업기사🔅 (9)
        • 컴퓨터활용능력 1급📼 (12)
      • ─────────── (0)
      • ◐ 기타 (113)
        • 알아두면 좋은 팁(tip)✨ (46)
        • 개발자의 일상🎈 (44)
        • 개발도서 서평🔍 (10)
        • 개발관련 세미나🎤 (2)
        • 블로그 꾸미기🎀 (9)
        • 사도신경 프로젝트🎚️ (2)
  • 인기 글

  • 최근 댓글

  • 태그

    CSS
    Database
    코딩
    BOJ
    Java
    꿀팁
    Error Note
    Oracle
    백준 티어
    SQL
    백준
    일상
    javascript
    jsp
    자바스크립트
    html
    Project
    코딩 테스트
    프로그래밍
    spring
  • 250x250
  • hELLO· Designed By정상우.v4.10.3
예르미(yermi)
[Student] Lombok 적용(@Getter, @Setter)
상단으로

티스토리툴바