diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..052fa33 --- /dev/null +++ b/.gitignore @@ -0,0 +1,117 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij + +### Intellij ### +# 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 Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +# End of https://www.toptal.com/developers/gitignore/api/intellij \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..dcd9ac7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,20 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.1' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /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 0000000..107acd3 --- /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 0000000..4b53eb3 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'calculator' + diff --git a/src/main/java/accumulator/Accumulator.java b/src/main/java/accumulator/Accumulator.java new file mode 100644 index 0000000..396a9d9 --- /dev/null +++ b/src/main/java/accumulator/Accumulator.java @@ -0,0 +1,6 @@ +package accumulator; + +public interface Accumulator { + + public int calculate(String calculator); +} diff --git a/src/main/java/accumulator/PostFixAccumulator.java b/src/main/java/accumulator/PostFixAccumulator.java new file mode 100644 index 0000000..14692c2 --- /dev/null +++ b/src/main/java/accumulator/PostFixAccumulator.java @@ -0,0 +1,65 @@ +package accumulator; + +import static operator.Operator.*; + +import java.util.Stack; +import operator.Operator; +import util.PatternValidator; + +public class PostFixAccumulator implements Accumulator { + + private int firstOperand; + private int secondOperand; + + @Override + public int calculate(String postfixExpression) { + Stack result = new Stack<>(); + String[] splitPostfixExpression = postfixExpression.split(" "); + for (String str : splitPostfixExpression) { + processToken(result, str); + } + return result.pop(); + } + + private void processToken(Stack result, String str) { + if (PatternValidator.checkOperatorValue(str)) { + processOperator(result, str); + } else if (!PatternValidator.checkOperatorValue(str)) { + processOperand(result, str); + } + } + + private void processOperand(Stack result, String str) { + result.push(Integer.parseInt(str)); + } + + private void processOperator(Stack result, String str) { + Operator value = stringToOperator(str); + calculate(result, value); + } + + private void calculate(Stack result, Operator value) { + switch (value) { + case PLUS: + firstOperand = result.pop(); + secondOperand = result.pop(); + result.push(secondOperand + firstOperand); + break; + case MINUS: + firstOperand = result.pop(); + secondOperand = result.pop(); + result.push(secondOperand - firstOperand); + break; + case MULTIPLY: + firstOperand = result.pop(); + secondOperand = result.pop(); + result.push(secondOperand * firstOperand); + break; + case DIVIDE: + firstOperand = result.pop(); + secondOperand = result.pop(); + result.push(secondOperand / firstOperand); + break; + } + } +} diff --git a/src/main/java/calculator/Calculator.java b/src/main/java/calculator/Calculator.java new file mode 100644 index 0000000..58a9f2f --- /dev/null +++ b/src/main/java/calculator/Calculator.java @@ -0,0 +1,71 @@ +package calculator; + +import accumulator.Accumulator; +import accumulator.PostFixAccumulator; +import convertor.InfixToPostfixConverter; +import input.ConsoleInput; +import java.util.List; +import output.ConsoleOutput; +import output.Output; +import repository.Repository; +import util.PatternValidator; + + +public class Calculator { + + private final int INQUIRY = 1; + private final int CALCULATE = 2; + + private Output output = new ConsoleOutput(); + + private Repository repository = new Repository(); + + public void run() { + ConsoleInput input = new ConsoleInput(); + while (true) { + try { + output.displayOptions(); + String selectInput = input.selectInput(); + PatternValidator.checkSelectValue(selectInput); + int select = Integer.parseInt(selectInput); + selectOptions(input, select); + } catch (IllegalArgumentException e) { + output.print(e.getMessage()); + } + } + } + + private void selectOptions(ConsoleInput input, int select) { + switch (select) { + case INQUIRY: + List result = repository.getResult(); + output.print(result); + break; + + case CALCULATE: + String expression = input.expressionInput(); + compute(expression); + break; + } + } + + private void compute(String expression) { + PatternValidator.checkExpressionValue(expression); + String postFixExpression = convertToPostfixExpression(expression); + String result = basicOperation(postFixExpression); + output.print(result); + repository.store(expression, result); + } + + private String basicOperation(String postFixExpression) { + Accumulator calculator = new PostFixAccumulator(); + String result = Integer.toString(calculator.calculate(postFixExpression)); + return result; + } + + private String convertToPostfixExpression(String expression) { + InfixToPostfixConverter infixToPostfixConverter = new InfixToPostfixConverter(); + String postFixExpression = infixToPostfixConverter.changeToPostFix(expression); + return postFixExpression; + } +} diff --git a/src/main/java/convertor/InfixToPostfixConverter.java b/src/main/java/convertor/InfixToPostfixConverter.java new file mode 100644 index 0000000..16c22b3 --- /dev/null +++ b/src/main/java/convertor/InfixToPostfixConverter.java @@ -0,0 +1,73 @@ +package convertor; + +import java.util.Arrays; +import java.util.Stack; +import operator.Operator; +import util.PatternValidator; + +public class InfixToPostfixConverter { + + private StringBuilder postfix = new StringBuilder(); + + + public String changeToPostFix(String expression) { + Stack operatorStack = new Stack(); + String[] splitExpression = expression.split(" "); + Arrays.stream(splitExpression).forEach(token -> { + processToken(operatorStack, token); + }); + while (!operatorStack.isEmpty()) { + postfix.append(operatorStack.pop()); + } + return postfix.toString(); + } + + private void processToken(Stack operatorStack, String token) { + if (PatternValidator.checkOperatorValue(token)) { + handleOperator(operatorStack, token); + } else if (!PatternValidator.checkOperatorValue(token)) { + handelOperand(token); + } + } + + private void handelOperand(String token) { + int value = Integer.parseInt(token); + postfix.append(value).append(" "); + } + + private void handleOperator(Stack operatorStack, String token) { + Operator currentOperator = Operator.stringToOperator(token); + int currentOperatorPriority = operatorPriority(currentOperator); + setOperatorToOperatorStack(operatorStack, token, currentOperatorPriority); + } + + private void setOperatorToOperatorStack(Stack operatorStack, String token, + int currentOperatorPriority) { + compareOperatorPriority(operatorStack, currentOperatorPriority); + operatorStack.add((token + " ")); + } + + private void compareOperatorPriority(Stack operatorStack, int currentOperatorPriority) { + while (!operatorStack.isEmpty()) { + Operator topStackOperator = Operator.stringToOperator(operatorStack.peek().substring(0, 1)); + int topStackOperatorPriority = operatorPriority(topStackOperator); + if (topStackOperatorPriority < currentOperatorPriority) { + break; + } + postfix.append(operatorStack.pop()); + } + } + + + public int operatorPriority(Operator operator) { + switch (operator) { + case PLUS: + case MINUS: + return 1; + case MULTIPLY: + case DIVIDE: + return 2; + } + return -1; + } +} diff --git a/src/main/java/input/ConsoleInput.java b/src/main/java/input/ConsoleInput.java new file mode 100644 index 0000000..6c65c6d --- /dev/null +++ b/src/main/java/input/ConsoleInput.java @@ -0,0 +1,33 @@ +package input; + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ConsoleInput implements Input { + + private BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); + + @Override + public String selectInput() { + String selectInput = ""; + try { + selectInput = bufferedReader.readLine(); + } catch (IOException e) { + throw new IllegalArgumentException("잘못된 옵션 선택입니다."); + } + return selectInput; + } + + @Override + public String expressionInput() { + String expressionInput = ""; + try { + expressionInput = bufferedReader.readLine(); + } catch (IOException e) { + throw new IllegalArgumentException("잘못된 식 입력입니다."); + } + return expressionInput; + } +} diff --git a/src/main/java/input/Input.java b/src/main/java/input/Input.java new file mode 100644 index 0000000..60c417c --- /dev/null +++ b/src/main/java/input/Input.java @@ -0,0 +1,9 @@ +package input; + +public interface Input { + + public String selectInput(); + + public String expressionInput(); + +} diff --git a/src/main/java/main.java b/src/main/java/main.java new file mode 100644 index 0000000..a2e66fc --- /dev/null +++ b/src/main/java/main.java @@ -0,0 +1,9 @@ + +import calculator.Calculator; + +public class main { + + public static void main(String[] args) { + new Calculator().run(); + } +} diff --git a/src/main/java/operator/Operator.java b/src/main/java/operator/Operator.java new file mode 100644 index 0000000..815c9b2 --- /dev/null +++ b/src/main/java/operator/Operator.java @@ -0,0 +1,25 @@ +package operator; + +public enum Operator { + PLUS("+"), MINUS("-"), DIVIDE("/"), MULTIPLY("*"); + + private final String value; + + Operator(String value) { + this.value = value; + } + + public String getValue() { + return this.value; + } + + public static Operator stringToOperator(String value) { + for (Operator operator : Operator.values()) { + if (operator.getValue().equals(value)) { + return operator; + } + } + throw new IllegalArgumentException("잘못된 입력값 입니다."); + } + +} diff --git a/src/main/java/output/ConsoleOutput.java b/src/main/java/output/ConsoleOutput.java new file mode 100644 index 0000000..111fb30 --- /dev/null +++ b/src/main/java/output/ConsoleOutput.java @@ -0,0 +1,27 @@ +package output; + + +import java.util.List; + +public class ConsoleOutput implements Output { + + @Override + public void print(List result) { + result.stream().forEach(System.out::println); + } + + @Override + public void print(String msg) { + System.out.println(msg); + } + + @Override + public void displayOptions() { + System.out.println("1.조회"); + System.out.println("2.계산"); + System.out.println(); + System.out.print("선택 : "); + } + + +} diff --git a/src/main/java/output/Output.java b/src/main/java/output/Output.java new file mode 100644 index 0000000..bcb4b03 --- /dev/null +++ b/src/main/java/output/Output.java @@ -0,0 +1,14 @@ +package output; + +import java.util.List; +import repository.Repository; + +public interface Output { + + + public void print(List result); + + public void print(String msg); + + public void displayOptions(); +} diff --git a/src/main/java/repository/Repository.java b/src/main/java/repository/Repository.java new file mode 100644 index 0000000..4ac107a --- /dev/null +++ b/src/main/java/repository/Repository.java @@ -0,0 +1,20 @@ +package repository; + +import java.util.ArrayList; +import java.util.List; + +public class Repository { + + private List list = new ArrayList<>(); + + public void store(String expression, String result) { + StringBuilder formattedExpression = new StringBuilder(expression).append(" = ").append(result); + list.add(formattedExpression.toString()); + + } + + public List getResult() { + return new ArrayList<>(list); + } + +} diff --git a/src/main/java/util/PatternValidator.java b/src/main/java/util/PatternValidator.java new file mode 100644 index 0000000..fe8754f --- /dev/null +++ b/src/main/java/util/PatternValidator.java @@ -0,0 +1,40 @@ +package util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PatternValidator { + + private static final Pattern EXPRESSIONREGEX = Pattern.compile( + "^\\d+(?: \\+ \\d+| - \\d+| \\* \\d+| \\/ \\d+)*$"); + + private static final Pattern OPTIONREGEX = Pattern.compile("^[12]+$"); + + private static final Pattern OPERATORREGEX = Pattern.compile("[\\+\\-\\*/]"); + + public static boolean checkExpressionValue(String expression) { + Matcher matcher = EXPRESSIONREGEX.matcher(expression); + if (!matcher.matches()) { + throw new IllegalArgumentException("잘못된 식 입력입니다."); + } + return true; + } + + + public static boolean checkSelectValue(String select) { + Matcher matcher = OPTIONREGEX.matcher(select); + if (!matcher.matches()) { + throw new IllegalArgumentException("잘못된 옵션 선택입니다"); + } + return true; + } + + public static boolean checkOperatorValue(String operator) { + Matcher matcher = OPERATORREGEX.matcher(operator); + if (!matcher.matches()) { + return false; + } + return true; + } + +} diff --git a/src/test/java/CalculatorTest.java b/src/test/java/CalculatorTest.java new file mode 100644 index 0000000..2dda79b --- /dev/null +++ b/src/test/java/CalculatorTest.java @@ -0,0 +1,59 @@ +import accumulator.Accumulator; +import accumulator.PostFixAccumulator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class CalculatorTest { + + + @ParameterizedTest + @DisplayName("덧셈") + @CsvSource(value = {"1 2 + 3 + : 6", "10 20 + 30 + : 60", + "100 200 + 300 + : 600"}, delimiter = ':') + public void postFixAddCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("뺼셈") + @CsvSource(value = {"1 2 - 3 -: -4", "10 30 - 20 -: -40", "300 200 - 1 - : 99"}, delimiter = ':') + public void postFixMinusCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("곱셈") + @CsvSource(value = {"1 2 * 3 *: 6", "10 20 * 30 *: 6000", + "100 200 * 300 * : 6000000"}, delimiter = ':') + public void postFixMultiplyCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("나눗셈") + @CsvSource(value = {"100 10 / 1 / : 10", "10 2 / : 5", "10000 20 / 10 / : 50"}, delimiter = ':') + public void postFixDivideCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("사칙연산") + @CsvSource(value = {"5 3 2 * + 8 4 / - : 9", "7 4 * 2 / 3 + 1 - : 16", + "9 5 - 2 * 6 3 / +: 10"}, delimiter = ':') + public void PostFixCalculate(String expression, int expectResult) { + PostFixAccumulator calculator = new PostFixAccumulator(); + int result = calculator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + +} diff --git a/src/test/java/ChangToPostfixTest.java b/src/test/java/ChangToPostfixTest.java new file mode 100644 index 0000000..5f3bca3 --- /dev/null +++ b/src/test/java/ChangToPostfixTest.java @@ -0,0 +1,19 @@ +import convertor.InfixToPostfixConverter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class ChangToPostfixTest { + + @ParameterizedTest + @DisplayName("중위 표기식 후위 표기식 변환") + @CsvSource(value = {"7 * 4 / 2 + 3 - 1 :'7 4 * 2 / 3 + 1 - '", + "9 - 5 * 2 + 6 / 3: '9 5 2 * - 6 3 / + '"}, delimiter = ':') + public void InfixToPostfixTest(String infixExpression, String postFinExpression) { + InfixToPostfixConverter calculator = new InfixToPostfixConverter(); + String result = calculator.changeToPostFix(infixExpression); + Assertions.assertEquals(postFinExpression, result); + } + +} diff --git a/src/test/java/RepositoryTest.java b/src/test/java/RepositoryTest.java new file mode 100644 index 0000000..43d4ed4 --- /dev/null +++ b/src/test/java/RepositoryTest.java @@ -0,0 +1,23 @@ +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import repository.Repository; + +public class RepositoryTest { + + private Repository repository; + + + @ParameterizedTest + @CsvSource(value = {"2 + 3, 5 : 4 * 5, 20", "10 / 2 : 5"}, delimiter = ':') + public void testStoreAndGetResult(String expression, String result) { + repository = new Repository(); + repository.store(expression, result); + List actuallyResult = repository.getResult(); + + Assertions.assertEquals(result, actuallyResult.get(0)); + } + +} + diff --git a/src/test/java/ValidationTest.java b/src/test/java/ValidationTest.java new file mode 100644 index 0000000..fe217f7 --- /dev/null +++ b/src/test/java/ValidationTest.java @@ -0,0 +1,44 @@ +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import util.PatternValidator; + +public class ValidationTest { + + @ParameterizedTest + @DisplayName("옵션 선택 테스트") + @ValueSource(strings = {"1", "2"}) + public void OptionSelectTest(String selectInput) { + boolean result = PatternValidator.checkSelectValue(selectInput); + Assertions.assertTrue(result); + } + + @ParameterizedTest + @DisplayName("옵션 선택 검증 테스트") + @ValueSource(strings = {"10000", "abc", "!!@@##"}) + public void OptionSelectValidationTest(String selectInput) { + Assertions.assertThrows(IllegalArgumentException.class, () -> { + PatternValidator.checkSelectValue(selectInput); + }); + } + + @ParameterizedTest + @DisplayName("식 입력 테스트") + @ValueSource(strings = {"3 + 1 + 2", "1 * 2 / 100 + 2 - 10"}) + public void inputExpressionTest(String input) { + boolean result = PatternValidator.checkExpressionValue(input); + Assertions.assertTrue(result); + } + + @ParameterizedTest + @DisplayName("식 입력 검증 테스트") + @ValueSource(strings = {"1*2/100+2-10", "!!@@##"}) + public void inputExpressionValidationTest(String input) { + Assertions.assertThrows(IllegalArgumentException.class, () -> { + PatternValidator.checkExpressionValue(input); + }); + } +} + +