숫자가 아닌 입력을 받았을 때
0으로 나누기 연산을 시도하였을 때

 

정상적으로 프로세스가 완료되었을 때

import java.util.Scanner;

public class HW1_calculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("::::::::::사칙연산 계산기::::::::::");
        int a = 0, b = 0; // 입력값 2개
        char c;   // 연산자 1개

        String input; // 검사를 위한 임시 String 변수

        // 첫번째 수 검사
        out: while (true) {
            System.out.println("첫번째 숫자를 입력해주세요.");
            System.out.print(">>> ");
            input = sc.next();
            for (int i=0; i<input.length(); i++) {
                if (input.charAt(i) > 57 || input.charAt(i) < 48) {
                    System.out.println("유효하지 않은 숫자");
                    break;
                } else {
                    a = Integer.parseInt(input);
                    break out;
                }
            }
        }

        // 연산자 입력 후 검사
        while (true) {
            System.out.println("연산자를 입력해주세요 (+, -, *, /)");
            System.out.print(">>> ");
            input = sc.next();
            c = input.charAt(0);
            if (c == '+' || c == '-' || c == '*' || c == '/') {
                break;
            } else {
                System.out.print("올바른 연산자가 아닙니다.\n\n");
            }
        }

        // 두번째 수 검사
        out: while (true) {
            System.out.println("두번째 숫자를 입력해주세요.");
            System.out.print(">>> ");
            input = sc.next();
            for (int i=0; i<input.length(); i++) {
                if (input.charAt(i) > 57 || input.charAt(i) < 48) {
                    System.out.println("유효하지 않은 숫자");
                    break;
                } else {
                    b = Integer.parseInt(input);
                    break out;
                }
            }
        }

        // 계산 후 출력
        System.out.print("\n");
        System.out.print("계산 결과\n");
        if (c == '+') {
            System.out.printf("%d %c %d = %d", a, c, b, a+b);
        } else if (c == '-') {
            System.out.printf("%d %c %d = %d", a, c, b, a-b);
        } else if (c == '*') {
            System.out.printf("%d %c %d = %d", a, c, b, a*b);
        } else if (c == '/') {
            if ( b == 0) {
                System.out.println("0으로 나눌 수 없습니다!");
            } else {
                System.out.printf("%d %c %d = %.2f", a, c, b, (double) a / b);
            }
        } else {
            System.out.println("예상하지 못한 오류 발생");
        }
    }
}

+ Recent posts