✅ 답안과 비교하여 스스로 코드 개선점 짚어보기 완료(2022.01.04)
BASIC1. 학생 정보 기록 프로그램
생성자를 이용한 초기화 / 설정자를 이용한 초기화 장단점을 구분하여 사용해야 한다.
이미 존재하는 정보 수정이 필요할 때 설정자(setter)를 쓰고, 초기에 많은 매개변수를 사용해야 할 때는 생성자를 이용함이 적합하다.
index를 별도 변수에 지정하여 출력문에도 활용하도록 한다.
입력 값을 판별할 때 (!('y' == ch || ch == 'Y')) 경우의 수를 모두 다룰 수도 있다.
하지만 String 클래스의 메소드 중 toLowerCase 소문자로 만들어주는 메소드를 쓰면 sc.nextLine().toLowerCase().charAt(0); (anwer != 'y') 조건만 판단해도 된다. 반대로 toUpperCase 쓸 수 있다.
아니면 답안을 애초에 char 아닌 String으로 받아서 sc.nextLine(); (answer.equalsIgnoreCase("Y"));처럼 표현할 수도 있다.
StudentDTO.class의 기본 생성자를 굳이 호출할 필요가 없는 문제다. 이미 매개변수 있는 생성자에 index 값을 부여한 뒤 입력 받은 값들을 차례로 등록하고 있기 때문이다.
또, 평균을 낼 때 getInformation()에서 ((kor+eng+math) / 3처럼 연산 식을 만들 수도 있지만, 출력을 위한 for문 안에서 sum/3 처리할 수가 있다.
학년 : 1
반 : 5
이름 : 홍길동
국어점수 : 40
영어점수 : 60
수학점수 : 70
계속 추가할 겁니까? (y/n) : y
학년 : 2
반 : 1
이름 : 김말똥
국어점수 : 70
영어점수 : 80
수학점수 : 100
계속 추가할 겁니까? (y/n) : y
학년 : 3
반 : 3
이름 : 강경순
국어점수 : 100
영어점수 : 75
수학점수 : 86
계속 추가할 겁니까? (y/n) : n
학년=1, 반=5, 이름=홍길동, 국어=40, 영어=60, 수학=70, 평균=56
학년=2, 반=1, 이름=김말똥, 국어=70, 영어=80, 수학=100, 평균=83
학년=3, 반=3, 이름=강경순, 국어=100, 영어=75, 수학=86, 평균=87
Application.class
package com.reminder.object_array_practice.student.run;
import java.util.Scanner;
import com.reminder.object_array_practice.student.model.dto.StudentDTO;
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StudentDTO[] student = new StudentDTO[10];
int index=0;
while(true) {
System.out.print("학년 : ");
int grade = scanner.nextInt();
System.out.print("반 : ");
int classroom = scanner.nextInt();
System.out.print("이름 : ");
scanner.nextLine(); //
String name = scanner.nextLine();
System.out.print("국어 : ");
int kor = scanner.nextInt();
System.out.print("영어 : ");
int eng = scanner.nextInt();
System.out.print("수학 : ");
int math = scanner.nextInt();
student[index++] = new StudentDTO(grade, classroom, name, kor, eng, math);
System.out.print("계속 추가하시겠습니까? (y/n) : ");
String yesOrNo = scanner.next();
if(!(yesOrNo.equalsIgnoreCase("y"))) {
break;
}
}
for(int i=0; i < index; i++) {
int sum = student[i].getKor() + student[i].getEng() + student[i].getMath();
System.out.println(student[i].getInformation() + ", 평균=" + sum/3);
}
}
}
StudentDTO.class
package com.reminder.object_array_practice.student.model.dto;
public class StudentDTO {
private int grade;
private int classroom;
private String name;
private int kor;
private int eng;
private int math;
/* 기본 생성자 */
public StudentDTO() {
}
/* 매개변수 있는 생성자 */
public StudentDTO(int grade, int classroom, String name, int kor, int eng, int math) {
this.grade = grade;
this.classroom = classroom;
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
}
/* 설정자(setter)와 접근자(getter) */
public void setGrade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setClassroom(int classroom) {
this.classroom = classroom;
}
public int getClassroom() {
return classroom;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getKor() {
return kor;
}
public void setEng(int eng) {
this.eng = eng;
}
public int getEng() {
return eng;
}
public void setMath(int math) {
this.math = math;
}
public int getMath() {
return math;
}
/* info */
public String getInformation() {
return "학년=" + grade + ", 반=" + classroom + ", 이름=" + name + ", 국어=" + kor + ", 영어=" + eng + ", 수학=" + math;
}
}
NORMAL1. 제품 정보 추가 및 조회 프로그램
===== 제품 관리 메뉴 =====
1. 제품 정보 추가
2. 제품 전체 조회
9. 프로그램 종료
메뉴 선택 : 3
잘못된 번호를 입력하셨습니다. 메뉴를 다시 선택하세요.
===== 제품 관리 메뉴 =====
1. 제품 정보 추가
2. 제품 전체 조회
9. 프로그램 종료
메뉴 선택 : 2
제품 번호=1, 제품명=January, 제품 가격=10000, 제품 세금=10.0
제품 번호=2, 제품명=February, 제품 가격=20000, 제품 세금=10.0
ProductDTO.class
package com.reminder.object_array_practice.product.model.dto;
import com.reminder.object_array_practice.product.manager.ProductManager;
public class ProductDTO {
private int pId;
private String pName;
private int price;
private double tax;
public ProductDTO() {
}
public ProductDTO(int pId, String pName, int price, double tax) {
this.pId = pId;
this.pName = pName;
this.price = price;
this.tax = tax;
ProductManager.count++;
}
public int getpId() {
return pId;
}
public void setpId(int pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public double getTax() {
return tax;
}
public void setTax(double tax) {
this.tax = tax;
}
public String getInformation() {
return "제품 번호=" + pId + ", 제품명=" + pName + ", 제품 가격=" + price + ", 제품 세금=" + tax;
}
}
ProductManager.class
초기화 블럭을 사용한다.
package com.reminder.object_array_practice.product.manager;
import java.util.Scanner;
import com.reminder.object_array_practice.product.model.dto.ProductDTO;
public class ProductManager {
private ProductDTO[] pro = null;
public static int count;
Scanner scanner = new Scanner(System.in);
{
pro = new ProductDTO[10];
}
public void mainMenu() {
int menu=0;
do {
System.out.println("===== 제품 관리 메뉴 =====");
System.out.println("1. 제품 정보 추가");
System.out.println("2. 제품 전체 조회");
System.out.println("9. 프로그램 종료");
System.out.print("메뉴 선택 : ");
menu = scanner.nextInt();
switch(menu) {
case 1 : productInput(); break;
case 2 : productPrint(); break;
case 9 : System.out.println("프로그램을 종료합니다."); return;
default : System.out.println("잘못된 번호를 입력하셨습니다. 메뉴를 다시 선택하세요."); break;
}
} while(menu != 9);
}
public void productInput() {
System.out.print("제품 번호 : ");
int pId = scanner.nextInt();
System.out.print("제품명 : ");
scanner.nextLine();
String pName = scanner.nextLine();
System.out.print("제품 가격 : ");
int price = scanner.nextInt();
System.out.print("제품 세금 : ");
double tax = scanner.nextDouble();
pro[count] = new ProductDTO(pId, pName, price, tax);
}
public void productPrint() {
for(int i=0; i < count; i++) {
System.out.println(pro[i].getInformation());
}
}
}
Application.class
두 문장으로 나누어 쓸 수 있는 호출 구문을 하나로 간추릴 수 있다.
package com.reminder.object_array_practice.product.run;
import com.reminder.object_array_practice.product.manager.ProductManager;
public class Application {
public static void main(String[] args) {
// ProductManager productManager = new ProductManager();
// productManager.mainMenu();
new ProductManager().mainMenu();
}
}
'Java' 카테고리의 다른 글
[JAVA] 9. 다형성 | 추상클래스 | 인터페이스 (1) | 2022.01.05 |
---|---|
[JAVA] 8. 상속 | super | 오버라이딩 (0) | 2022.01.04 |
[JAVA] 7. 객체배열 (0) | 2022.01.03 |
[JAVA] 6-4. 클래스변수, 인스턴스변수, 지역변수, 초기화 순서 (0) | 2022.01.03 |
[JAVA/수업 과제 practice] 배열 | 다차원 배열 Lv. 3~4 (0) | 2022.01.02 |