diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..f75cd2815 --- /dev/null +++ b/.gitignore @@ -0,0 +1,145 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all,gradle,java +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,gradle,java + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all,gradle,java \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 000000000..9a295ca74 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/README.md b/README.md index c1c982e55..ff60fab60 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,6 @@ # java_calculator 자바 계산기 구현 미션 Repository입니다. -### 이곳은 공개 Repo입니다. -1. 여러분의 포트폴리오로 사용하셔도 됩니다. -2. 때문에 이 repo를 fork한 뒤 -3. 여러분의 개인 Repo에 작업하며 -4. 이 Repo에 PR을 보내어 멘토의 코드 리뷰와 피드백을 받으세요. - -### Branch 명명 규칙 + 팀의 PR규칙 정하기 -1. 여러분 repo는 알아서 해주시고 😀(본인 레포니 main으로 하셔두 되져) -2. prgrms-be-devcourse/spring-board 레포로 PR시 branch는 gituser_id을 적어주세요 :) - - base repo : `여기repo` base : `username` ← head repo : `여러분repo` compare : `main`또는 `github_id` -3. 실제 진행할 PR규칙은 멘토+팀원들과 정하여 진행해주세요 :) - - ← head repo : `여러분repo` compare : `main`로 할지 - - 또는 ← head repo : `여러분repo` compare : `github_id`로 할지 -- 참고 : [Github 위치 및 피드백 기준 가이드](https://www.notion.so/backend-devcourse/Github-e1a0908a6bbf4aeaa5a62981499bb215) - ### 과제를 통해 기대하는 역량 - 깃허브를 통한 코드리뷰를 경험해보자 diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..dca5fe47a --- /dev/null +++ b/build.gradle @@ -0,0 +1,25 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + + implementation 'org.apache.commons:commons-lang3:3.12.0' + + implementation 'org.projectlombok:lombok' + implementation 'org.projectlombok:lombok:1.18.22' + + testImplementation(platform('org.junit:junit-bom:5.9.3')) + testImplementation('org.junit.jupiter:junit-jupiter') +} + +test { + useJUnitPlatform() +} \ No newline at end of file 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..da1db5f04 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +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 100644 index 000000000..a69d9cb6c --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/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 \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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..f127cfd49 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@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% equ 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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +: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/org/example/App.java b/src/main/java/org/example/App.java new file mode 100644 index 000000000..45f0978ec --- /dev/null +++ b/src/main/java/org/example/App.java @@ -0,0 +1,19 @@ +package org.example; + +import org.example.engine.Calculator; +import org.example.engine.repository.CalculationRepository; +import org.example.engine.repository.OrderedInmemoryCalculationRepository; + +public class App { + public static void main(String[] args) { + + Console console = new Console(); + CalculationRepository calculationRepository = new OrderedInmemoryCalculationRepository(); + new Calculator(console, calculationRepository).run(); + + } + +} + + + diff --git a/src/main/java/org/example/Console.java b/src/main/java/org/example/Console.java new file mode 100644 index 000000000..cb5fbbf0e --- /dev/null +++ b/src/main/java/org/example/Console.java @@ -0,0 +1,34 @@ +package org.example; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import org.apache.commons.lang3.StringUtils; +import org.example.exception.CaculatorApplicationException; + +public class Console { + private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + public int inputSelectMode() throws IOException, CaculatorApplicationException { + System.out.println("1. 조회"); + System.out.println("2. 계산"); + String inputSelectMode = br.readLine(); + if (!(inputSelectMode.equals("1") || inputSelectMode.equals("2"))) { + throw new CaculatorApplicationException("Invalid input"); + } + int mode = Integer.parseInt(inputSelectMode); + return mode; + } + + public String inputExpression() throws IOException { + System.out.println("연산식을 입력해라"); + String inputExpression = br.readLine(); + return inputExpression; + } + + public void outputSelectResult(int mode) { + System.out.printf("선택 : %d%n", mode); + } + +} diff --git a/src/main/java/org/example/engine/Calculator.java b/src/main/java/org/example/engine/Calculator.java new file mode 100644 index 000000000..835bf9779 --- /dev/null +++ b/src/main/java/org/example/engine/Calculator.java @@ -0,0 +1,146 @@ +package org.example.engine; + +import org.apache.commons.lang3.StringUtils; +import org.example.Console; +import org.example.engine.enums.ArithmeticOperator; +import org.example.exception.CaculatorApplicationException; +import org.example.engine.model.CalculationResult; +import org.example.engine.repository.CalculationRepository; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Stack; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class Calculator implements Runnable { + private Console console; + private CalculationRepository calculationRepository; + + public Calculator(Console console, CalculationRepository calculationRepository) { + this.console = console; + this.calculationRepository = calculationRepository; + } + + @Override + public void run() { + + while (true) { + + try { + int mode = console.inputSelectMode(); + console.outputSelectResult(mode); + switch (mode) { + case 1: + loadHistory(); + break; + case 2: + compute(); + break; + } + } catch (CaculatorApplicationException e1) { + System.out.println(e1.getMessage()); + continue; + } catch (IOException e2) { + System.out.println(e2.getMessage()); + continue; + } + + } + + } + + public void compute() throws IOException, CaculatorApplicationException { + String inputExpression = console.inputExpression(); + String preprocessedExpression = preprocess(inputExpression); + if (!validateExpression(preprocessedExpression)) { + throw new CaculatorApplicationException("Invalid expression"); + } + List parseExpression = parseExpression(preprocessedExpression); + List postfixExpression = infixToPostfix(parseExpression); + Double result = calculate(postfixExpression); + System.out.println(result); + saveHistory(new CalculationResult(inputExpression, result)); + } + + public void loadHistory() { + List historyList = calculationRepository.findAll(); + for (CalculationResult calculationResult : historyList) { + calculationResult.printInfo(); + } + } + + public String preprocess(String rowExpression) { + String preprocessedExpression = rowExpression.trim(); + preprocessedExpression = preprocessedExpression.replaceAll("\\s+", ""); + preprocessedExpression = preprocessedExpression.replaceAll("([+\\-*/])", " $1 "); + + return preprocessedExpression; + } + + public boolean validateExpression(String expression) { + String regex = "^\\d+(\\s*[+\\-*/]\\s*\\d+)*$"; + return Pattern.matches(regex, expression); + } + + public List parseExpression(String expression) { + return Arrays.stream(expression.split(" ")).collect(Collectors.toList()); + } + + public List infixToPostfix(List infixExpression) { + List postfixExpression = new ArrayList<>(); + Stack st = new Stack<>(); + for (String ele : infixExpression) { + if (StringUtils.isNumeric(ele)) { + postfixExpression.add(ele); + continue; + } + + if (st.isEmpty()) { + st.add(ele); + continue; + } + + ArithmeticOperator prevOperator = ArithmeticOperator.getArithmeticOperator(st.peek()); + ArithmeticOperator tempOperator = ArithmeticOperator.getArithmeticOperator(ele); + if (ArithmeticOperator.comparePriority(prevOperator, tempOperator) < 0) { + st.add(ele); + } else { + while (!st.isEmpty()) + postfixExpression.add(st.pop()); + st.add(ele); + } + } + + while (!st.isEmpty()) + postfixExpression.add(st.pop()); + + return postfixExpression; + } + + public double calculate(List postfixExpression) throws CaculatorApplicationException { + + Stack st = new Stack<>(); + + for (String ele : postfixExpression) { + if (StringUtils.isNumeric(ele)) { + st.add(ele); + continue; + } + + Double right = Double.parseDouble(st.pop()); + Double left = Double.parseDouble(st.pop()); + String arithmeticOperator = ele; + st.add(String.valueOf(ArithmeticOperator.calculate(arithmeticOperator, left, right))); + } + + return Double.parseDouble(st.pop()); + } + + public int saveHistory(CalculationResult calculationResult) { + return calculationRepository.save(calculationResult); + } + +} diff --git a/src/main/java/org/example/engine/enums/ArithmeticOperator.java b/src/main/java/org/example/engine/enums/ArithmeticOperator.java new file mode 100644 index 000000000..f118f8e4e --- /dev/null +++ b/src/main/java/org/example/engine/enums/ArithmeticOperator.java @@ -0,0 +1,53 @@ +package org.example.engine.enums; + +import java.util.Arrays; +import java.util.function.BiFunction; + +import org.example.exception.CaculatorApplicationException; + +public enum ArithmeticOperator { + ADDITION("+", 1, (left, right) -> left + right), + SUBTRACTION("-", 1, (left, right) -> left - right), + MULTIPLICATION("*", 2, (left, right) -> left * right), + DIVISION("/", 2, (Dividend, Divisor) -> { + if (Divisor != 0) { + return Dividend / Divisor; + } else { + throw new CaculatorApplicationException("Cannot divide by zero"); + } + + }); + + private String arithmeticOperator; + private final int priority; + private BiFunction expression; + + ArithmeticOperator(String arithmeticOperator, int priority, BiFunction expression) { + this.arithmeticOperator = arithmeticOperator; + this.priority = priority; + this.expression = expression; + } + + public String getArithmeticOperator() { + return arithmeticOperator; + } + + public int getPriority() { + return priority; + } + + public static ArithmeticOperator getArithmeticOperator(String arithmeticOperator) { + return Arrays.stream(values()) + .filter(o -> o.arithmeticOperator.equals(arithmeticOperator)) + .findFirst().orElseThrow(() -> new CaculatorApplicationException("Invalid operator.")); + } + + public static int comparePriority(ArithmeticOperator operator1, ArithmeticOperator operator2) { + return Integer.compare(operator1.getPriority(), operator2.getPriority()); + } + + public static double calculate(String arithmeticOperator, double num1, double num2) { + return getArithmeticOperator(arithmeticOperator).expression.apply(num1, num2); + } + +} diff --git a/src/main/java/org/example/engine/model/CalculationResult.java b/src/main/java/org/example/engine/model/CalculationResult.java new file mode 100644 index 000000000..0ddfa4b0a --- /dev/null +++ b/src/main/java/org/example/engine/model/CalculationResult.java @@ -0,0 +1,18 @@ +package org.example.engine.model; + +import lombok.ToString; + +@ToString +public class CalculationResult { + private String expression; + private Double result; + + public CalculationResult(String expression, Double result) { + this.expression = expression; + this.result = result; + } + + public void printInfo() { + System.out.printf("%s = %f%n", this.expression, this.result); + } +} diff --git a/src/main/java/org/example/engine/repository/CalculationRepository.java b/src/main/java/org/example/engine/repository/CalculationRepository.java new file mode 100644 index 000000000..aa9426625 --- /dev/null +++ b/src/main/java/org/example/engine/repository/CalculationRepository.java @@ -0,0 +1,16 @@ +package org.example.engine.repository; + +import org.example.engine.model.CalculationResult; + +import java.util.List; + +public interface CalculationRepository { + public int save(CalculationResult calculationResult); + + public List findAll(); + + public void clear(); + + public int size(); + +} diff --git a/src/main/java/org/example/engine/repository/OrderedInmemoryCalculationRepository.java b/src/main/java/org/example/engine/repository/OrderedInmemoryCalculationRepository.java new file mode 100644 index 000000000..8e893329f --- /dev/null +++ b/src/main/java/org/example/engine/repository/OrderedInmemoryCalculationRepository.java @@ -0,0 +1,38 @@ +package org.example.engine.repository; + +import org.example.engine.model.CalculationResult; + +import java.util.*; + +public class OrderedInmemoryCalculationRepository implements CalculationRepository { + private static Long id; + private static Map memoryDB; + + public OrderedInmemoryCalculationRepository() { + id = 0L; + this.memoryDB = new LinkedHashMap<>(); + } + + @Override + public int save(CalculationResult calculationResult) { + memoryDB.put(id, calculationResult); + id++; + return 0; + } + + @Override + public List findAll() { + return new ArrayList<>(memoryDB.values()); + } + + @Override + public void clear() { + memoryDB.clear(); + id = 0L; + } + + @Override + public int size() { + return memoryDB.size(); + } +} diff --git a/src/main/java/org/example/exception/CaculatorApplicationException.java b/src/main/java/org/example/exception/CaculatorApplicationException.java new file mode 100644 index 000000000..e2dce6641 --- /dev/null +++ b/src/main/java/org/example/exception/CaculatorApplicationException.java @@ -0,0 +1,13 @@ +package org.example.exception; + +import lombok.Getter; + +@Getter +public class CaculatorApplicationException extends RuntimeException { + private String message; + + public CaculatorApplicationException(String message) { + this.message = message; + } + +} diff --git a/src/test/java/org/example/engine/CalculatorTest.java b/src/test/java/org/example/engine/CalculatorTest.java new file mode 100644 index 000000000..51df49430 --- /dev/null +++ b/src/test/java/org/example/engine/CalculatorTest.java @@ -0,0 +1,136 @@ +package org.example.engine; + +import org.example.Console; +import org.example.engine.repository.CalculationRepository; +import org.example.engine.repository.OrderedInmemoryCalculationRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +class CalculatorTest { + Console console; + CalculationRepository calculationRepository; + Calculator calculator; + + @BeforeEach + void setUp() { + this.console = new Console(); + this.calculationRepository = new OrderedInmemoryCalculationRepository(); + this.calculator = new Calculator(this.console, this.calculationRepository); + } + + @DisplayName("사칙연산 공백 전처리 테스트") + @Test + void preprocessExpressionTest() { + String rowExpression = " 1 + 2 3 / 3 * 8 - 2 "; + String preprocessedExpression = "1 + 23 / 3 * 8 - 2"; + assertEquals(preprocessedExpression, calculator.preprocess(rowExpression)); + } + + @DisplayName("사칙연산 입력 검증 통과 테스트") + @ParameterizedTest + @MethodSource("passValidateExpressionTestData") + void passValidateExpressionTest(String expression) { + boolean expected = true; + boolean actual = calculator.validateExpression(expression); + assertEquals(expected, actual); + } + + @DisplayName("사칙연산 입력 검증 실페 테스트") + @ParameterizedTest + @MethodSource("failValidateExpressionTestData") + void failValidateExpressionTest(String expression) { + boolean expected = false; + boolean actual = calculator.validateExpression(expression); + assertEquals(expected, actual); + } + + @DisplayName("문자열 형태의 연산 입력값을 공백을 기준으로 분리한 리스트 변환") + @Test + void parseExpressionTest() { + String expression = "1 + 2 / 3 * 4 - 5"; + List expected = Arrays.asList("1", "+", "2", "/", "3", "*", "4", "-", "5"); + List actual = calculator.parseExpression(expression); + assertEquals(expected, actual); + + } + + @DisplayName("연산자 우선순위를 반영하여 중위식 표현의 연산입력값을 후위식으로 표현") + @ParameterizedTest + @MethodSource("infixToPostfixTestData") + void infixToPostfixTest(List input, List output) { + List expected = output; + List actual = calculator.infixToPostfix(input); + assertEquals(expected, actual); + } + + @DisplayName("연산자 우선순위를 반영하여 중위식 표현의 연산입력값을 후위식으로 표현") + @ParameterizedTest + @MethodSource("caluateTestData") + void calulateTest(List postfixExpression, Double output) { + System.out.println(calculator.calculate(postfixExpression)); + Double expected = output; + Double actual = calculator.calculate(postfixExpression); + assertEquals(expected, actual); + } + + @DisplayName("0으로 나눌시 예외 반환") + @Test + void calulateTest2() { + + List postfixExpression = Arrays.asList("1", "0", "/"); + + assertThrows(ArithmeticException.class, () -> { + double result = calculator.calculate(postfixExpression); + }); + + } + + private static List passValidateExpressionTestData() { + return Arrays.asList( + "1 + 2 / 3 * 4 - 5", + "1 + 2 / 3 * 4 - 5", + "1+2/3*4", + "2222222222+33333333/4*777777-2" + ); + } + + private static List failValidateExpressionTestData() { + return Arrays.asList( + "1 + 2 / 3 * 4 -", + "1 + + 2 / 3 * 4 - 5", + "1+2/ 3 4", + " " + ); + } + + private static Stream infixToPostfixTestData() { + + return Stream.of( + Arguments.of(Arrays.asList("1", "+", "2", "*", "3"), Arrays.asList("1", "2", "3", "*", "+")), + Arguments.of(Arrays.asList("1", "-", "2", "/", "3"), Arrays.asList("1", "2", "3", "/", "-")), + Arguments.of(Arrays.asList("1", "+", "2", "-", "3"), Arrays.asList("1", "2", "+", "3", "-")), + Arguments.of(Arrays.asList("1", "/", "2", "*", "3"), Arrays.asList("1", "2", "/", "3", "*")) + ); + } + + private static Stream caluateTestData() { + + return Stream.of( + Arguments.of(Arrays.asList("1", "2", "3", "*", "+"), 6.0), + Arguments.of(Arrays.asList("1", "2", "3", "/", "-"), 1.6666666666666665), + Arguments.of(Arrays.asList("1", "2", "+", "3", "-"), 6.0), + Arguments.of(Arrays.asList("1", "2", "/", "3", "*"), 3.5) + ); + } + +} \ No newline at end of file diff --git a/src/test/java/org/example/engine/repository/OrderedInmemoryCalculationRepositoryTest.java b/src/test/java/org/example/engine/repository/OrderedInmemoryCalculationRepositoryTest.java new file mode 100644 index 000000000..067a042c8 --- /dev/null +++ b/src/test/java/org/example/engine/repository/OrderedInmemoryCalculationRepositoryTest.java @@ -0,0 +1,45 @@ +package org.example.engine.repository; + +import org.example.engine.model.CalculationResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class OrderedInmemoryCalculationRepositoryTest { + CalculationRepository calculationRepository; + + @BeforeEach + void setup() { + this.calculationRepository = new OrderedInmemoryCalculationRepository(); + } + + @Test + void save() { + String expression = "1 + 2 + 3"; + Double result = 6.0; + CalculationResult calculationResult = new CalculationResult(expression, result); + assertEquals(0L, calculationRepository.save(calculationResult)); + } + + @Test + void findAll() { + String expression = "1 + 2 + 3"; + Double result = 6.0; + for (int i = 0; i < 10; i++) { + calculationRepository.save(new CalculationResult(expression, result)); + } + assertEquals(10, calculationRepository.findAll().size()); + } + + @Test + void clear() { + String expression = "1 + 2 + 3"; + Double result = 6.0; + for (int i = 0; i < 10; i++) { + calculationRepository.save(new CalculationResult(expression, result)); + } + calculationRepository.clear(); + assertEquals(0, calculationRepository.size()); + } +} \ No newline at end of file