diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..e4798d7c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/** +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..5944f7075 --- /dev/null +++ b/build.gradle @@ -0,0 +1,26 @@ +plugins { + id 'java' +} + +group = 'co.programmers' +version = '1.0-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(11) + } +} + +repositories { + mavenCentral() +} + +test { + useJUnitPlatform() +} + +dependencies { + implementation 'org.jetbrains:annotations:24.0.0' + testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1' + testImplementation 'org.assertj:assertj-core:3.11.1' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..249e5832f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..3b29eaad1 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Jun 08 19:11:48 KST 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..1b6c78733 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..bcf30bf6c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'java-calculator' + diff --git a/src/main/java/co/programmers/App.java b/src/main/java/co/programmers/App.java new file mode 100644 index 000000000..82ef4a1d9 --- /dev/null +++ b/src/main/java/co/programmers/App.java @@ -0,0 +1,17 @@ +package co.programmers; + +import co.programmers.domain.CalculatorApp; +import co.programmers.view.CalculatorInputView; +import co.programmers.view.CalculatorOutputView; +import co.programmers.view.InputView; +import co.programmers.view.OutputView; + +public class App { + + public static void main(String[] args) { + InputView inputView = new CalculatorInputView(); + OutputView outputView = new CalculatorOutputView(); + CalculatorApp calculatorApp = new CalculatorApp(inputView, outputView); + calculatorApp.run(); + } +} diff --git a/src/main/java/co/programmers/domain/Calculation.java b/src/main/java/co/programmers/domain/Calculation.java new file mode 100644 index 000000000..e1889f246 --- /dev/null +++ b/src/main/java/co/programmers/domain/Calculation.java @@ -0,0 +1,59 @@ +package co.programmers.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Calculation { + + private List parsedExpression; + private List operators; + private Expression expression; + + public Calculation(Expression expression) { + this.expression = expression; + parsedExpression = new ArrayList<>(); + operators = new ArrayList<>(); + } + + public Double calculate() throws ArithmeticException { + parsedExpression = expression.split(); + operators = extractOperators(); + Operator.decideCalculationOrder(operators); + for (String operator : operators) { + int operatorPosition = parsedExpression.indexOf(operator); + Double[] operands = extractOperands(operator); + Double calculationRes = Operator.calculate(operator, operands[0], operands[1]); + storeIntermediateResult(operatorPosition, calculationRes); + removeCompletedExpression(operatorPosition, operands.length); + } + return calcFinalResult(); + } + + private void removeCompletedExpression(int operatorPosition, int count) { + for (int cnt = 0; cnt <= count; cnt++) { + parsedExpression.remove(operatorPosition); + } + } + + private void storeIntermediateResult(int operatorPosition, Double calculationRes) { + parsedExpression.add(operatorPosition - 1, String.valueOf(calculationRes)); + } + + private Double[] extractOperands(String operator) { + int operatorIdx = parsedExpression.indexOf(operator); + Double operand1 = Double.parseDouble(parsedExpression.get(operatorIdx - 1)); + Double operand2 = Double.parseDouble(parsedExpression.get(operatorIdx + 1)); + return new Double[] {operand1, operand2}; + } + + private List extractOperators() { + expression.eliminateWhiteSpace(); + List parsed = expression.split("\\d+"); + parsed.removeIf(String::isEmpty); + return parsed; + } + + private Double calcFinalResult() { + return Double.parseDouble(parsedExpression.get(0)); + } +} diff --git a/src/main/java/co/programmers/domain/CalculatorApp.java b/src/main/java/co/programmers/domain/CalculatorApp.java new file mode 100644 index 000000000..0ac2d96ca --- /dev/null +++ b/src/main/java/co/programmers/domain/CalculatorApp.java @@ -0,0 +1,58 @@ +package co.programmers.domain; + +import co.programmers.exception.ExceptionMessage; +import co.programmers.view.CalculatorOutputView; +import co.programmers.view.InputView; +import co.programmers.view.OutputView; + +public class CalculatorApp { + + private final InputView inputView; + private final OutputView outputView; + + public CalculatorApp(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + UserMenu userMenu; + do { + CalculatorOutputView.printMenuChoiceGuide(); + userMenu = UserMenu.get(inputView.inputUserMenu()); + executeSelectedMenu(userMenu); + } while (userMenu != UserMenu.TERMINATE); + } + + private void executeSelectedMenu(UserMenu userMenu) { + switch (userMenu) { + case INQUIRY: + inquiry(); + break; + case CALCULATE: + calculate(); + break; + case TERMINATE: + break; + default: + outputView.printMessage(ExceptionMessage.INVALID_INPUT); + break; + } + } + + public void inquiry() { + //TODO + } + + public void calculate() { + try { + CalculatorOutputView.printCalculationGuide(); + Expression expression = inputView.inputExpression(); + Calculation calculator = new Calculation(expression); + Double output = calculator.calculate(); + outputView.printCalculationResult(output); + } catch (ArithmeticException arithmeticException) { + System.out.println(arithmeticException.getMessage()); + } + } +} diff --git a/src/main/java/co/programmers/domain/Expression.java b/src/main/java/co/programmers/domain/Expression.java new file mode 100644 index 000000000..3f8b189b9 --- /dev/null +++ b/src/main/java/co/programmers/domain/Expression.java @@ -0,0 +1,43 @@ +package co.programmers.domain; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import co.programmers.exception.ExceptionMessage; + +public class Expression { + + private static final Pattern EXPRESSION_FORMAT = Pattern.compile("(\\d+\\s[\\+\\-\\*\\/]\\s)+\\d+"); + private static final String DELIMITER = " "; + private String expression; + + public Expression(String expression) { + this.expression = expression; + if (expression == null || expression.isEmpty()) { + throw new IllegalArgumentException(ExceptionMessage.EMPTY_INPUT); + } + if (!validate()) { + throw new ArithmeticException(ExceptionMessage.INVALID_EXPRESSION); + } + } + + private boolean validate() { + + Matcher matcher = EXPRESSION_FORMAT.matcher(expression); + return matcher.matches(); + } + + public List split() { + return new ArrayList<>(List.of(expression.split(DELIMITER))); + } + + public List split(String delimiter) { + return new ArrayList<>(List.of(expression.split(delimiter))); + } + + public void eliminateWhiteSpace() { + expression = expression.replaceAll("\\s", ""); + } +} diff --git a/src/main/java/co/programmers/domain/Operator.java b/src/main/java/co/programmers/domain/Operator.java new file mode 100644 index 000000000..e26205020 --- /dev/null +++ b/src/main/java/co/programmers/domain/Operator.java @@ -0,0 +1,51 @@ +package co.programmers.domain; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.BiFunction; + +import co.programmers.exception.ExceptionMessage; + +public enum Operator { + ADDITION("+", 2, (operand1, operand2) -> operand1 + operand2), + SUBTRACTION("-", 2, (operand1, operand2) -> operand1 - operand2), + MULTIPLICATION("*", 1, (operand1, operand2) -> operand1 * operand2), + DIVISION("/", 1, (operand1, operand2) -> { + if (operand2 == 0) { + throw new ArithmeticException(ExceptionMessage.DIVIDED_BY_ZERO); + } + return operand1 / operand2; + }); + + private final String symbol; + private final int priority; + private final BiFunction operation; + + private Operator(String symbol, int priority, BiFunction operation) { + this.symbol = symbol; + this.priority = priority; + this.operation = operation; + } + + public static Double calculate(String operator, Double operand1, Double operand2) { + return getSymbol(operator).operation.apply(operand1, operand2); + } + + public static Operator getSymbol(Object operator) { + return Arrays.stream(values()) + .filter(o -> o.symbol.equals(operator)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(ExceptionMessage.INVALID_INPUT)); + } + + public static void decideCalculationOrder(List operators) { + Collections.sort(operators, (operator1, operator2) -> + Integer.compare(getSymbol(operator1).getPriority(), getSymbol(operator2).getPriority()) + ); + } + + public int getPriority() { + return priority; + } +} diff --git a/src/main/java/co/programmers/domain/UserMenu.java b/src/main/java/co/programmers/domain/UserMenu.java new file mode 100644 index 000000000..93e719a3a --- /dev/null +++ b/src/main/java/co/programmers/domain/UserMenu.java @@ -0,0 +1,20 @@ +package co.programmers.domain; + +import java.util.Arrays; + +public enum UserMenu { + INQUIRY(1), CALCULATE(2), TERMINATE(3), ERROR(-9999); + + private final Integer menu; + + private UserMenu(Integer value) { + this.menu = value; + } + + public static UserMenu get(Integer input) { + return Arrays.stream(values()) + .filter(menuNum -> menuNum.menu.equals(input)) + .findFirst() + .orElse(ERROR); + } +} diff --git a/src/main/java/co/programmers/exception/ExceptionMessage.java b/src/main/java/co/programmers/exception/ExceptionMessage.java new file mode 100644 index 000000000..08cb0c899 --- /dev/null +++ b/src/main/java/co/programmers/exception/ExceptionMessage.java @@ -0,0 +1,12 @@ +package co.programmers.exception; + +public class ExceptionMessage { + + public static final String DIVIDED_BY_ZERO = "0으로 나눌 수 없습니다."; + public static final String INVALID_INPUT = "잘못된 입력입니다"; + public static final String INVALID_EXPRESSION = "잘못된 수식입니다"; + public static final String EMPTY_INPUT = "입력이 비어있습니다"; + + private ExceptionMessage() { + } +} diff --git a/src/main/java/co/programmers/view/CalculatorInputView.java b/src/main/java/co/programmers/view/CalculatorInputView.java new file mode 100644 index 000000000..8001d8d3f --- /dev/null +++ b/src/main/java/co/programmers/view/CalculatorInputView.java @@ -0,0 +1,22 @@ +package co.programmers.view; + +import java.util.Scanner; + +import co.programmers.domain.Expression; + +public class CalculatorInputView implements InputView { + + private static final Scanner SCANNER = new Scanner(System.in); + + @Override + public Integer inputUserMenu() { + Integer userInput = SCANNER.nextInt(); + SCANNER.nextLine(); + return userInput; + } + + @Override + public Expression inputExpression() throws ArithmeticException { + return new Expression(SCANNER.nextLine()); + } +} diff --git a/src/main/java/co/programmers/view/CalculatorOutputView.java b/src/main/java/co/programmers/view/CalculatorOutputView.java new file mode 100644 index 000000000..38b96b69a --- /dev/null +++ b/src/main/java/co/programmers/view/CalculatorOutputView.java @@ -0,0 +1,26 @@ +package co.programmers.view; + +public class CalculatorOutputView implements OutputView { + public static void printCalculationGuide() { + System.out.println("1 + 2 * 3와 같은 형식으로 계산하고자 하는 식을 입력하세요."); + System.out.print("> "); + } + + public static void printMenuChoiceGuide() { + System.out.println("\n[다음 중 원하시는 항목을 숫자로 입력하세요]"); + System.out.println("1. 조회"); + System.out.println("2. 계산"); + System.out.println("3. 종료"); + System.out.print("> 선택 : "); + } + + @Override + public void printCalculationResult(Double result) { + System.out.println(">> 결과 : " + result); + } + + @Override + public void printMessage(String message) { + System.out.println(message); + } +} diff --git a/src/main/java/co/programmers/view/InputView.java b/src/main/java/co/programmers/view/InputView.java new file mode 100644 index 000000000..6bd3f37dd --- /dev/null +++ b/src/main/java/co/programmers/view/InputView.java @@ -0,0 +1,10 @@ +package co.programmers.view; + +import co.programmers.domain.Expression; + +public interface InputView { + + Integer inputUserMenu(); + + Expression inputExpression(); +} diff --git a/src/main/java/co/programmers/view/OutputView.java b/src/main/java/co/programmers/view/OutputView.java new file mode 100644 index 000000000..cea9ff73d --- /dev/null +++ b/src/main/java/co/programmers/view/OutputView.java @@ -0,0 +1,8 @@ +package co.programmers.view; + +public interface OutputView { + + void printCalculationResult(Double result); + + void printMessage(String message); +} diff --git a/src/test/java/CalculatorTest.java b/src/test/java/CalculatorTest.java new file mode 100644 index 000000000..309be1b04 --- /dev/null +++ b/src/test/java/CalculatorTest.java @@ -0,0 +1,97 @@ +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.Arrays; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +import co.programmers.domain.Calculation; +import co.programmers.domain.Expression; +import co.programmers.domain.Operator; + +class CalculatorTest { + + static ArrayList[] generateData() { + return new ArrayList[] { + new ArrayList<>(Arrays.asList("+", "*", "*", "-", "/")), + }; + } + + @ParameterizedTest + @ValueSource(strings = { + "1 + 25 % 4", + "3 ^ 3 - 22 / 3", + "22 # 3 - 4 + 15", + "2 ! 3" + }) + @DisplayName("입력된 수식이 사칙 연산 이외의 연산 기호를 포함하는 경우 예외를 던진다.") + void ExpressionTest(String input) { + assertThatThrownBy(() -> new Expression(input)).isInstanceOf(ArithmeticException.class); + } + + @ParameterizedTest + @ValueSource(strings = { + "1 + 25 % 4 + A", + "AB2 * 3 - 22 + 3", + "22 + A - 4 + 15", + "[ 2 * 3 / ]" + }) + @DisplayName("입력된 수식이 숫자와 사칙 연산 기호 이외의 문자를 포함하는 경우 예외를 던진다.") + void ExpressionWithInvalidCharactersTest(String input) { + assertThatThrownBy(() -> new Expression(input)).isInstanceOf(ArithmeticException.class); + } + + @ParameterizedTest + @MethodSource("generateData") + @DisplayName("여러 연산자들이 주어졌을 때 연산 순서를 올바르게 결정할 수 있다") + void OperatordecideCalculationOrderTest(ArrayList operators) { + ArrayList operatorOrder = new ArrayList<>(Arrays.asList("*", "*", "/", "+", "-")); + Operator.decideCalculationOrder(operators); + assertThat(operators).containsExactlyElementsOf(operatorOrder); + } + + @ParameterizedTest + @NullAndEmptySource + @DisplayName("입력된 수식이 null 이거나 빈 공백인 경우 예외를 던진다.") + void ExpressionNullAndEmptyTest(String expression) { + assertThatThrownBy(() -> new Expression(expression)) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = { + "1 + 25 * 4 / 0", + "3 / 0", + "22 - 3 + 4 / 0", + }) + @DisplayName("0으로 나누는 경우 예외를 던진다") + void calculateDividedByZeroTest(String inputExpression) { + Expression expression = new Expression(inputExpression); + Calculation calculation = new Calculation(expression); + assertThatThrownBy(() -> calculation.calculate()) + .isInstanceOf(ArithmeticException.class); + } + + @ParameterizedTest + @CsvSource(value = { + "1111 + 10000 : 11111.0", + "200 - 100 : 100.0", + "20 / 5 : 4.0", + "30 * 3 : 90.0", + "2 + 6 * 2 / 8 : 3.5", + "21 + 3 * 4 - 33 / 2 : 16.5", + "42 / 3 * 4 - 2 : 54.0"}, + delimiter = ':') + @DisplayName("주어진 수식에 대해 정확한 계산을 할 수 있다") + void OperatorCalculateTest(String input, final Double result) { + Expression expression = new Expression(input); + Calculation calculation = new Calculation(expression); + assertThat(calculation.calculate()).isEqualTo(result); + } +}