diff --git a/src/main/java/Calculator.java b/src/main/java/Calculator.java new file mode 100644 index 0000000..dd45a13 --- /dev/null +++ b/src/main/java/Calculator.java @@ -0,0 +1,33 @@ +public class Calculator { + public double calculate(String expression) { + String[] tokens = expression.split(" "); + double currentResult = Double.parseDouble(tokens[0]); + + for (int i = 1; i < tokens.length; i += 2) { + String operator = tokens[i]; + double number = Double.parseDouble(tokens[i + 1]); + + switch (operator) { + case "+": + currentResult += number; + break; + case "-": + currentResult -= number; + break; + case "*": + currentResult *= number; + break; + case "/": + if (number == 0) { + throw new ArithmeticException("0으로 나눌 수 없습니다."); + } + currentResult /= number; + break; + default: + System.out.println("지원하지 않는 연산자입니다: " + operator); + return 0; + } + } + return currentResult; + } +} diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 5415de6..5e37612 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,5 +1,22 @@ +import java.util.Scanner; + public class Main { public static void main(String[] args) { - System.out.println("1 + 1 = 2"); + Scanner scanner = new Scanner(System.in); + System.out.println("계산할 수식을 입력하세요 (예: 30 + 20 / 2 * 4):"); + String expression = scanner.nextLine(); + + Validator validator = new Validator(); + if (validator.isValid(expression)) { + Calculator calculator = new Calculator(); + try { + double result = calculator.calculate(expression); + System.out.println("결과: " + result); + } catch (ArithmeticException e) { + System.out.println("계산 중 오류가 발생했습니다: " + e.getMessage()); + } + } else { + System.out.println("잘못된 수식 형식입니다. 다시 입력해주세요."); + } } } diff --git a/src/main/java/Validator.java b/src/main/java/Validator.java new file mode 100644 index 0000000..b57e29f --- /dev/null +++ b/src/main/java/Validator.java @@ -0,0 +1,34 @@ +public class Validator { + public boolean isValid(String expression) { + String[] tokens = expression.split(" "); + + if (tokens.length % 2 == 0) { + return false; + } + + if (!isNumeric(tokens[0])) { + return false; + } + + for (int i = 1; i < tokens.length; i += 2) { + if (!isOperator(tokens[i]) || !isNumeric(tokens[i + 1])) { + return false; + } + } + + return true; + } + + private boolean isNumeric(String str) { + try { + Double.parseDouble(str); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + private boolean isOperator(String str) { + return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"); + } +}