
개별 프로젝트로 사칙연산 + 가 되는 계산기 개발
Scanner 활용Scanner 활용if or switchfor or whileCalculator클래스 생성Calculator 클래스 생성Calculator 클래스 생성Calculator클래스가 활용될 수 있도록 수정Calculator클래스가 담당Calculator클래스의 연산 결과를 저장하는 필드에 저장Calculator클래스의 연산 결과를 저아하고 있는 컬렉션 필드에 직접 접근하지 못하도록 수정(캡슐화)Calculator클래스에 저장된 연산 결과들 중 가장 먼저 저장된 데이터를 삭제하는 기능을 가진 메서드를 구현한 후 App 클래스의 main메서드에 삭제 메서드가 활용될 수 있도록 수정Main.java
import java.util.Objects;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a, b, result;
String input;
char c;
Calculator calculator = new Calculator();
Scanner sc = new Scanner(System.in);
for (int i = 1; ; i++) {
System.out.printf("\n========계산 준비 완료 / 사용량 : %d회==========\n\n", i);
System.out.println("첫번째 숫자를 입력하세요.");
System.out.print(": ");
while (!sc.hasNextInt()){
System.out.println("잘못된 값을 입력하였습니다.");
System.out.print(": ");
sc.next();
}
a = sc.nextInt();
System.out.println("두번째 숫자를 입력하세요.");
System.out.print(": ");
while (!sc.hasNextInt()){
System.out.println("잘못된 값을 입력하였습니다.");
System.out.print(": ");
sc.next();
}
b = sc.nextInt();
System.out.println("사칙연산 기호를 입렵하세요(+, -, *, /)");
System.out.print(": ");
while(true){
input = sc.next();
c = input.charAt(0);
if(c == '+' || c == '-' || c == '*' || c == '/'){
break;
} else{
System.out.println("잘못된 값을 입력하였습니다. 입력값: " + c );
System.out.print(": ");
}
}
//연산 처리는 Calculator class에서만 진행
result = calculator.calculate(a, b, c);
System.out.println("\n"+ a + c + b + "=" + result);
calculator.removeresult(); // 오래된 데이터 삭제
System.out.println("최근 계산값");
// getter를 사용해 데이터 받기
for (String history : calculator.getHistory()) {
System.out.println(history);
}
System.out.print("종료 하시려면 'exit'를 입력해주세요: ");
String out = sc.next();
if (Objects.equals(out, "exit")){
break;
}
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Calculator {
private static List<String> history; //정보 은닉
private static final int maxSize = 10;
// 생성자
public Calculator() {
this.history = new ArrayList<>();
}
//기능
public int calculate(int a, int b, char c) {
int result = 0;
String output;
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b == 0) {
System.out.println("분모에는 0이 들어갈 수 없습니다." + "\n");
break;
}
result = a / b;
break;
}
output = a + " " + c + " " + b + " = " + result;
setHistory(output); //setHistory에서 저장
return result;
}
// 데이터 저장
public void setHistory(String savedata){
history.add(savedata);
}
// 원본 보호를 위해 복사본 반환
public List<String> getHistory() {
return new ArrayList<>(history);
}
//오래된 데이터 삭제 기능 구현
//maxSize를 넘는 갯수가 저장된다면 첫번째 데이터부터 삭제
public void removeresult(){
if(history.size() > maxSize) {
history.remove(0);
}
}
}
최종 결과