내배캠 TIL 10일차

오병택·2025년 2월 28일

내배캠

목록 보기
32/73

10일차 요약

lv1 개선사항 반영, lv2 계산기, 코드 리뷰

lv1

package com.example.calculator;

import java.util.InputMismatchException;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean exit = true;
        while (exit) {
            long x=0;
            long y=0;
            while (true) {
                try {
                    System.out.print("첫 번째 양의 정수(0 포함)를 입력해주세요: ");
                    x = scanner.nextLong();
                    System.out.print("두 번째 양의 정수(0 포함)를 입력해주세요: ");
                    y = scanner.nextLong();

                    if (x < 0 || y < 0) {
                        System.out.println("음수를 적으셨습니다. 다시 입력해주세요.");
                        continue;
                    }

                } catch (InputMismatchException e) {
                    scanner.nextLine();
                    System.out.println("숫자만 입력해주세요");
                    continue;
                }
                break;
            }

            while (true) {
                System.out.print("사칙연산 기호를 입력하세요: ");
                char z = scanner.next().charAt(0);
                switch (z) {
                    case '+' -> System.out.println("더한 값: " + (x + y));
                    case '-' -> System.out.println("뺀 값: " + (x - y));
                    case '*' -> System.out.println("곱한 값: " + (x * y));
                    case '/' -> {
                        if (y == 0) {
                            System.out.println("0으로 나눌 수 없습니다");
                            continue;
                        }
                        double result = (x % y == 0) ? (x / y) : (x / (double)y);
                        System.out.println(result);
                    }
                    default -> {
                        System.out.println("연산기호가 잘못됐습니다");
                        continue;
                    }
                }
                break;
            }

            scanner.nextLine();
            System.out.println("더 계산하시겠습니까? (exit 입력시 종료, 다른 입력시 계속)");
            String s = scanner.nextLine();
            if (s.equals("exit")) {
                exit = false;
                System.out.println("종료하겠습니다");
            }
        }
    }

}

개선사항을 반영하여 lv1을 다시 짜봤다. 확실히 전보다는 깔끔해진 게 좋은 것 같다.

lv2

코드 1

package com.example.calculator;

import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        Calculator cal = new Calculator();
        Scanner scanner = new Scanner(System.in);
        boolean exit = true;
        while (exit) {
            long x;
            long y;
            Object result;
            while (true) {
                try {
                    System.out.print("첫 번째 양의 정수(0 포함)를 입력해주세요: ");
                    x = scanner.nextLong();
                    System.out.print("두 번째 양의 정수(0 포함)를 입력해주세요: ");
                    y = scanner.nextLong();
                    if (x < 0 || y < 0) {
                        System.out.println("음수를 적으셨습니다. 다시 입력해주세요.");
                        continue;
                    }

                } catch (InputMismatchException e) {
                    scanner.nextLine();
                    System.out.println("숫자만 입력해주세요");
                    continue;
                }
                while (true) {
                    System.out.print("사칙연산 기호를 입력하세요: ");
                    char oper = scanner.next().charAt(0);
                    result = Calculator.calculate(x, oper, y); // 계산 값을 반환
                    if (result.equals('x')) { // 예외 발생시 문자 x값이 반환되어 실행
                        continue;
                    }
                    System.out.println("계산 값: " + result);
                    break;
                }

                System.out.println("값을 저장소에 저장합니다");
                List<Object> newResultSave = cal.getResultSave(); // 튜터님 개선 사항 적용x
                newResultSave.add(result);
                cal.setResultSave(newResultSave);
                cal.showResultSave();

                System.out.println("저장소에 저장된 첫 번째 값을 삭제를 원하시면 1, 아니면 0을 써주세요");
                int s = scanner.nextInt();
                if (s == 1) {
                    cal.removeResult();
                    cal.showResultSave();
                }
                break;
            }

            scanner.nextLine();
            System.out.println("더 계산하시겠습니까? (exit 입력시 종료, 다른 입력시 계속)");
            String q = scanner.nextLine();
            if (q.equals("exit")) {
                exit = false;
                System.out.println("종료하겠습니다");
            }
        }
    }

}

코드 2

package com.example.calculator;

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

public class Calculator {
    private List<Object> resultSave = new ArrayList<>();

    public static Object calculate(long x, char oper, long y) {
        Object result = switch (oper) {
            case '+' -> x + y;
            case '-' -> x - y;
            case '*' -> x * y;
            case '/' -> {
                if (y == 0) {
                    System.out.println("0으로 나눌 수 없으므로 x를 반환합니다");
                    yield 'x';
                }
                yield x / (double) y;
            }
            default -> {
                System.out.println("연산기호가 잘못됐으므로 x를 반환합니다");
                yield 'x';
            }
        };
        return result;
    }

    public List<Object> getResultSave() {
        return this.resultSave;
    }

    public void setResultSave(List<Object> resultSave) {
        this.resultSave = resultSave;
    }

    public void removeResult() {
        if (resultSave.isEmpty()) {
            System.out.println("저장소가 비어있습니다");
        }
        resultSave.remove(0);
    }

    public void showResultSave() {
        System.out.println(resultSave);
    }
}

고민한 부분

  • 컬렉션 타입을 어떤 타입으로 하지?
  • 메서드 안에서 모든 계산이 가능하게 어떻게 하지?
  • 나누기값만 실수로 바꾸고 싶은데?

해결한 부분

  • 메서드 안에 switch문을 쓰면 됨
  • Object 타입으로 받으면 여러가지 값을 받을 수 있음

코드 리뷰

일단 튜터님에게 내가 개념을 모르는 부분이 있어서 물어봤더니 잘 알려주셔서 개념은 이해가 잘 되었다.

튜터님이 알려준 개선사항

코드 중에 getter로 굳이 여기로 가져와서 바꿔서 다시 넣어주는 것보단 가져오지 않고 그곳에서 바꾸는 게 더 효율적이라고 알려주셨다.

팀원분들이 알려준 개선사항

  • Object 타입을 쓰지 말고 타입을 지정해주는 것이 좋다. 개발하는 사람만 어떤 타입인지 알고 다른 사람은 잘 모른다.
  • 클래스를 상세하게 나눠주면 좋다.

느낀 점

lv2를 만들어 보았는데 하나씩 고민하고 해결하는 게 은근 재밌었다. 물론 코드를 잘 짰다고 할 수 없지만 실행이 되게끔 만들어가는 과정을 집중을 해서 그런가 시간이 사라졌다. 확실히 강의 듣고 이해하려고 하는 것보다 직접 무언가를 만드는 게 더 재밌는 것 같다. 개선사항 적용을 하고 주석도 깔끔하게 쓰고 나서 lv3 갈 실력은 아닌 것 같긴 하지만 발가락만 담궈봐야 겠다.

profile
걱정하지 말고 일단 해봐!

0개의 댓글