추가 수정 코드
Main.java
public class Main {
public static void main(String[] args) {
App.main(args);
}
}
App.java
import java.util.Objects;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
//Calculator 호출
Calculator calculator = new Calculator();
//Scanner 활성화
Scanner sc = new Scanner(System.in);
//무한 반복을 위한 for 문
for (int i = 1; ; i++) {
System.out.printf("\n========계산 준비 완료 / 사용량 : %d회==========\n\n", i-1);
//연산을 위한 값 입력받기
int fstVal = getdataval(sc, "첫번째 숫자를 입력하세요.");
char mathSymbol = getdatasymol(sc, "사칙연산 기호를 입렵하세요(+, -, *, /)");
int sndVal = getdataval(sc, "두번째 숫자를 입력하세요.");
//연산 처리(Calculator.java)
int result = calculator.calculate(fstVal, sndVal, mathSymbol);
System.out.printf("결과값 :\n%d %c %d = %d\n\n", fstVal, mathSymbol, sndVal, result);
//getter 를 사용해 데이터 받기
System.out.println("최근 계산값");
for (String history : calculator.getHistory()) {
System.out.println(history);
}
System.out.println();
//종료 문구 확인
System.out.println("종료 하시려면 'exit'를 입력해주세요: ");
String out = sc.next();
if (Objects.equals(out, "exit")){
break;
}
}
//Scanner 비활성화
sc.close();
}
//정수 입력받기 매서드
private static int getdataval(Scanner sc, String msg){
System.out.println(msg);
System.out.print(": ");
while (!sc.hasNextInt()){
System.out.println("잘못된 값을 입력하였습니다.");
System.out.print(": ");
sc.next();
}
int val = sc.nextInt();
System.out.println();
return val;
}
// 기호 입력받기 매서드
private static char getdatasymol(Scanner sc, String msg){
System.out.println(msg);
System.out.print(": ");
while(true){
String input = sc.next();
char math_symbol = input.charAt(0);
System.out.println();
if(math_symbol == '+' || math_symbol == '-' || math_symbol == '*' || math_symbol == '/'){
return math_symbol;
} else{
System.out.println("잘못된 값을 입력하였습니다.");
System.out.print(": ");
}
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Calculator {
private List<String> history; //정보 은닉
private static final int maxSize = 10;
// 생성자
public Calculator() {
this.history = new ArrayList<>();
}
//기능
public int calculate(int a, int b, char math_symbol) {
int result = 0;
String savedata;
switch (math_symbol) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b == 0) {
System.out.println("분모에는 0이 들어갈 수 없습니다." + "\n");
return 0;
}
result = a / b;
break;
}
savedata = a + " " + math_symbol + " " + b + " = " + result;
setHistory(savedata); //setHistory 에서 저장
return result;
}
// 데이터 저장
public void setHistory(String savedata){
history.add(savedata);
removeresult();
}
// 원본 보호를 위해 복사본 반환
public List<String> getHistory() {
return new ArrayList<>(history);
}
//오래된 데이터 삭제 기능 구현
public void removeresult(){
if(history.size() > maxSize) {
history.remove(0);
}
}
}
가독성 향상을 위한 변수명 변경
a => fstVal
b => sndVal
c => mathSymol
결과값 출력 println에서 printf로 변경
Main.java파일에서는 App.java만 호출 하도록 설정
정수와 기호를 받는 부분을 메서드로 분리
기존 코드
private static List<String> history; // static으로 선언
public Calculator() {
this.history = new ArrayList<>();
}
변경 코드
private List<String> history;
public Calculator() {
this.history = new ArrayList<>();
}
static변수는 클래스에 속하고 모든 인스턴스가 공유
기존 코드는 여러 객체가 같은 기록을 공유 할 수 있다는 장점이 있으나 생성자 실행 시 데이터가 초기화 될 위험이 있다.
Calculator 한개만 사용함으로 유지해도 상관 없으나, 유지 할 것이라면 static초기화 블록을 사용하는 것이 더 효과적
기존 코드
case '/':
if (b == 0) {
System.out.println("분모에는 0이 들어갈 수 없습니다." + "\n");
break;
}
변경 코드
case '/':
if (b == 0) {
System.out.println("분모에는 0이 들어갈 수 없습니다." + "\n");
return 0;
}
break에서 return 0으로 변경함으로 분모를 0으로 입력 시 history에 저장하지 않음
기존 코드(Main.Java)
calculator.removeresult(); // 오래된 데이터 삭제
변경 코드(Calculaotr.java)
public void setHistory(String savedata){
history.add(savedata);
removeresult();
}
removeresult();을 Main.java에서 Calculaotr의 setHistory로 위치를 변경함으로 데이터 저장 후 안정적으로 삭제 동작 수행