diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..db1db659a --- /dev/null +++ b/.gitignore @@ -0,0 +1,171 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,intellij,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=java,intellij,gradle + +### 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 +.idea + +# 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 + +### 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/java,intellij,gradle \ No newline at end of file diff --git a/README.md b/README.md index c1c982e55..fd89f24ca 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,22 @@ # 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) +자바 계산기 구현 미션 Repository 입니다. ### 과제를 통해 기대하는 역량 -- 깃허브를 통한 코드리뷰를 경험해보자 -- 기본적인 테스트 코드 작성 및 활용하는 능력해보자 -- 스스로 OOP를 생각하고 코드로 옮길 수 있는 능력해보자 +- 깃허브를 통한 코드리뷰를 경험 +- 기본적인 테스트 코드 작성 및 활용하는 능력 +- 스스로 OOP를 생각하고 코드로 옮길 수 있는 능력 ### 요구사항 - 콘솔로 구현입니다.(스윙으로 구현하시는 분들 계실까봐) - 객체지향적인 코드로 계산기 구현하기 - - [ ] 더하기 - - [ ] 빼기 - - [ ] 곱하기 - - [ ] 나누기 - - [ ] 우선순위(사칙연산) -- [ ] 테스트 코드 구현하기 -- [ ] 계산 이력을 맵으로 데이터 저장기능 만들기 + - [x] 더하기 + - [x] 빼기 + - [x] 곱하기 + - [x] 나누기 + - [x] 우선순위(사칙연산) +- [x] 테스트 코드 구현하기 +- [x] 계산 이력을 맵으로 데이터 저장기능 만들기 - 애플리케이션이 동작하는 동안 데이터베이스 외에 데이터를 저장할 수 있는 방법을 고안해보세요. - (선택) 정규식 사용 diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..162af0be5 --- /dev/null +++ b/build.gradle @@ -0,0 +1,21 @@ +plugins { + id 'java' +} + +group 'com.programmers.devcourse' +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.assertj:assertj-core:3.24.2' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.2' +} + +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..41d9927a4 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..41dfb8790 --- /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-7.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 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/CalculatorApplication.java b/src/main/java/CalculatorApplication.java new file mode 100644 index 000000000..a102d5a05 --- /dev/null +++ b/src/main/java/CalculatorApplication.java @@ -0,0 +1,13 @@ +import computation.PostfixComputer; +import computation.PostfixConverter; +import io.Calculator; +import repository.CalculatorHistoryRepository; + +import java.io.IOException; + +public class CalculatorApplication { + public static void main(String[] args) throws IOException { + Calculator calculator = new Calculator(new PostfixConverter(), new PostfixComputer(), new CalculatorHistoryRepository()); + calculator.runApplication(); + } +} diff --git a/src/main/java/computation/Converter.java b/src/main/java/computation/Converter.java new file mode 100644 index 000000000..6a17c0139 --- /dev/null +++ b/src/main/java/computation/Converter.java @@ -0,0 +1,7 @@ +package computation; + +import java.util.List; + +public interface Converter { + List convert(String expression); +} diff --git a/src/main/java/computation/Operator.java b/src/main/java/computation/Operator.java new file mode 100644 index 000000000..85b4f8690 --- /dev/null +++ b/src/main/java/computation/Operator.java @@ -0,0 +1,35 @@ +package computation; + +import exception.ZeroDivisionException; +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Operator { + ADD("+", (num1, num2) -> num1 + num2), + SUBTRACT("-", (num1, num2) -> num1 - num2), + MULTIPLY("*", (num1, num2) -> num1 * num2), + DIVIDE("/", (num1, num2) -> { + if (num2 == 0) + throw new ZeroDivisionException(); + return num1 / num2; + }); + + private final String operator; + private final BiFunction expression; + + Operator(String operator, BiFunction expression) { + this.operator = operator; + this.expression = expression; + } + + public static Operator getOperator(String getString) { + return Arrays.stream(Operator.values()) + .filter(s -> s.operator.equals(getString)) + .findFirst() + .get(); + } + + public int operate(Integer num1, Integer num2) { + return expression.apply(num1, num2); + } +} diff --git a/src/main/java/computation/PostfixComputer.java b/src/main/java/computation/PostfixComputer.java new file mode 100644 index 000000000..93671aa37 --- /dev/null +++ b/src/main/java/computation/PostfixComputer.java @@ -0,0 +1,25 @@ +package computation; + +import validation.Validator; + +import java.util.List; +import java.util.Stack; + +public class PostfixComputer { + public int calculate(List postfixExpression) { + Stack calculationStack = new Stack<>(); + + for (String item : postfixExpression) { + if (Validator.isNumber(item)) { + calculationStack.push(Integer.parseInt(item)); + } else if (Validator.isOperator(item)) { + Integer operand2 = calculationStack.pop(); + Integer operand1 = calculationStack.pop(); + + Operator operator = Operator.getOperator(item); + calculationStack.push(operator.operate(operand1, operand2)); + } + } + return calculationStack.pop(); + } +} diff --git a/src/main/java/computation/PostfixConverter.java b/src/main/java/computation/PostfixConverter.java new file mode 100644 index 000000000..d76896f15 --- /dev/null +++ b/src/main/java/computation/PostfixConverter.java @@ -0,0 +1,76 @@ +package computation; + +import validation.Validator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Stack; + +public class PostfixConverter implements Converter { + private final StringBuilder sb = new StringBuilder(); + private final Map priority = Map.of( + "(", 0, + "+", 1, + "-", 1, + "*", 2, + "/", 2 + ); + + private boolean checkHigherPriority(Stack operatorStack, String item) { + return priority.get(operatorStack.peek()) >= priority.get(item); + } + + public void addElement(List list) { + if (sb.length() > 0) { + list.add(sb.toString()); + sb.setLength(0); + } + } + + @Override + public List convert(String expression) { + List postfix = new ArrayList<>(); + + Stack operatorStack = new Stack<>(); + String[] infixArray = expression.split(""); + sb.setLength(0); + + for (int i = 0; i < infixArray.length; i++) { + // 숫자라면 단순히 추가 + if (Validator.isNumber(infixArray[i])) { + sb.append(infixArray[i]); + + if (i == infixArray.length - 1) { + postfix.add(sb.toString()); + } + } else { + addElement(postfix); + + if (Validator.isOperator(infixArray[i])) { + // 연산자라면 먼저 우선순위 계산 + if (!operatorStack.isEmpty()) { + while (!operatorStack.isEmpty() && checkHigherPriority(operatorStack, infixArray[i])) { + postfix.add(operatorStack.pop()); + } + } + operatorStack.push(infixArray[i]); + } else if (Validator.isOpenBrackets(infixArray[i])) { + operatorStack.push(infixArray[i]); + } else if (Validator.isCloseBrackets(infixArray[i])) { + // 괄호에 대한 처리 + while (!operatorStack.isEmpty()) { + String poppedItem = operatorStack.pop(); + if (Validator.isOpenBrackets(poppedItem)) break; + postfix.add(poppedItem); + } + } + } + } + + while (!operatorStack.isEmpty()) { + postfix.add(operatorStack.pop()); + } + return postfix; + } +} diff --git a/src/main/java/exception/ZeroDivisionException.java b/src/main/java/exception/ZeroDivisionException.java new file mode 100644 index 000000000..39e5aaab9 --- /dev/null +++ b/src/main/java/exception/ZeroDivisionException.java @@ -0,0 +1,8 @@ +package exception; + +public class ZeroDivisionException extends RuntimeException { + private static final String MESSAGE = "0으로는 나눌 수 없습니다."; + public ZeroDivisionException() { + super(MESSAGE); + } +} diff --git a/src/main/java/io/Calculator.java b/src/main/java/io/Calculator.java new file mode 100644 index 000000000..6f3dfac49 --- /dev/null +++ b/src/main/java/io/Calculator.java @@ -0,0 +1,86 @@ +package io; + +import computation.Converter; +import computation.PostfixComputer; +import exception.ZeroDivisionException; +import repository.Repository; +import util.StringUtil; +import validation.Validator; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Calculator { + private final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + private final Converter converter; + private final PostfixComputer calculator; + private final Repository repository; + + public Calculator(Converter converter, PostfixComputer calculator, Repository repository) { + this.converter = converter; + this.calculator = calculator; + this.repository = repository; + } + + public void printMenu() { + System.out.println(MenuMessage.SELECT.getMessage()); + System.out.println(MenuMessage.CALCULATION.getMessage()); + System.out.println(MenuMessage.EXIT.getMessage()); + System.out.print(MenuMessage.CHOOSE.getMessage()); + } + + public String getUserInput() throws IOException { + return br.readLine(); + } + + public void runInquiry() { + System.out.println(DisplayMessage.SPLIT_LINE.getMessage()); + repository.inquiry(); + System.out.println(DisplayMessage.SPLIT_LINE.getMessage()); + } + + public void runCalculator() throws IOException { + String getInput = StringUtil.removeWhiteSpace(getUserInput()); + if (!Validator.isRightExpression(getInput)) { + System.out.println(DisplayMessage.WRONG_EXPRESSION.getMessage()); + return; + } + + try { + int result = calculator.calculate(converter.convert(getInput)); + repository.save(getInput, result); + System.out.print(DisplayMessage.OUTPUT.getMessage()); + System.out.println(result); + } catch (ZeroDivisionException e) { + System.out.println(e.getMessage()); + } + } + + + public void runApplication() throws IOException { + while (true) { + printMenu(); + + String getChoice = getUserInput(); + if (Validator.isNotNumber(getChoice)) { + System.out.println(DisplayMessage.BAD_REQUEST.getMessage()); + continue; + } + + int choice = Integer.parseInt(getChoice); + if (choice == Menu.QUERY.getMenuNumber()) { + // 조회 + runInquiry(); + } else if (choice == Menu.CALCULATE.getMenuNumber()) { + // 계산 + runCalculator(); + } else if (choice == Menu.EXIT.getMenuNumber()) { + // 종료 + System.exit(0); + } else { + System.out.println(DisplayMessage.BAD_REQUEST.getMessage()); + } + } + } +} diff --git a/src/main/java/io/DisplayMessage.java b/src/main/java/io/DisplayMessage.java new file mode 100644 index 000000000..96d012996 --- /dev/null +++ b/src/main/java/io/DisplayMessage.java @@ -0,0 +1,18 @@ +package io; + +public enum DisplayMessage { + OUTPUT("계산 결과 : "), + BAD_REQUEST("잘못된 명령입니다!"), + WRONG_EXPRESSION("잘못된 계산식입니다!"), + SPLIT_LINE("=================="); + + private final String message; + + DisplayMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/io/Menu.java b/src/main/java/io/Menu.java new file mode 100644 index 000000000..4718c1743 --- /dev/null +++ b/src/main/java/io/Menu.java @@ -0,0 +1,17 @@ +package io; + +public enum Menu { + QUERY(1), + CALCULATE(2), + EXIT(3); + + private final int menuNumber; + + Menu(int menuNumber) { + this.menuNumber = menuNumber; + } + + public int getMenuNumber() { + return menuNumber; + } +} diff --git a/src/main/java/io/MenuMessage.java b/src/main/java/io/MenuMessage.java new file mode 100644 index 000000000..dfe481878 --- /dev/null +++ b/src/main/java/io/MenuMessage.java @@ -0,0 +1,18 @@ +package io; + +public enum MenuMessage { + SELECT("1. 조회"), + CALCULATION("2. 계산"), + EXIT("3. 종료"), + CHOOSE("선택 : "); + + private final String message; + + MenuMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/repository/CalculatorHistoryRepository.java b/src/main/java/repository/CalculatorHistoryRepository.java new file mode 100644 index 000000000..16cac0c4a --- /dev/null +++ b/src/main/java/repository/CalculatorHistoryRepository.java @@ -0,0 +1,24 @@ +package repository; + +import java.util.ArrayList; +import java.util.List; + +public class CalculatorHistoryRepository implements Repository { + private static final List repository = new ArrayList<>(); + private final StringBuilder sb = new StringBuilder(); + + @Override + public void inquiry() { + repository.forEach(System.out::println); + } + + @Override + public void save(String record, int result) { + sb.setLength(0); + sb.append(record); + sb.append("="); + sb.append(result); + + repository.add(sb.toString()); + } +} diff --git a/src/main/java/repository/Repository.java b/src/main/java/repository/Repository.java new file mode 100644 index 000000000..ec7f0faab --- /dev/null +++ b/src/main/java/repository/Repository.java @@ -0,0 +1,6 @@ +package repository; + +public interface Repository { + void inquiry(); + void save(String record, int result); +} diff --git a/src/main/java/util/StringUtil.java b/src/main/java/util/StringUtil.java new file mode 100644 index 000000000..2d6a1ae7c --- /dev/null +++ b/src/main/java/util/StringUtil.java @@ -0,0 +1,7 @@ +package util; + +public class StringUtil { + public static String removeWhiteSpace(String targetExpr) { + return targetExpr.replace(" ", ""); + } +} diff --git a/src/main/java/validation/Validator.java b/src/main/java/validation/Validator.java new file mode 100644 index 000000000..05d62cec8 --- /dev/null +++ b/src/main/java/validation/Validator.java @@ -0,0 +1,55 @@ +package validation; + +import java.util.Stack; + +public class Validator { + private static final String NUMBER_PATTERN = "^[0-9]+"; + private static final String OPERATOR_PATTERN = "^[-+*/]"; + private static final String EXPRESSION_SEQUENCE = "^(([0-9]+[-+*/])+[0-9]+$)|([0-9]+)"; + + public static boolean isNumber(String getString) { + return getString.matches(NUMBER_PATTERN); + } + + public static boolean isNotNumber(String getString) { + return !isNumber(getString); + } + + public static boolean isOperator(String getString) { + return getString.matches(OPERATOR_PATTERN); + } + + public static boolean isOpenBrackets(String getString) { + return getString.equals("("); + } + + public static boolean isCloseBrackets(String getString) { + return getString.equals(")"); + } + + public static boolean checkBrackets(String getExpr) { + Stack bracketStack = new Stack<>(); + String[] exprArray = getExpr.split(""); + + for (String elem : exprArray) { + if (isOpenBrackets(elem)) { + bracketStack.push(elem); + } else if (isCloseBrackets(elem)) { + if (bracketStack.isEmpty()) { + return false; + } + bracketStack.pop(); + } + } + return bracketStack.isEmpty(); + } + + public static boolean expressionSequenceCheck(String getExpression) { + getExpression = getExpression.replace("(", "").replace(")", ""); + return getExpression.matches(EXPRESSION_SEQUENCE); + } + + public static boolean isRightExpression(String getExpression) { + return checkBrackets(getExpression) && expressionSequenceCheck(getExpression); + } +} diff --git a/src/test/java/computation/PostfixComputerTest.java b/src/test/java/computation/PostfixComputerTest.java new file mode 100644 index 000000000..133ee518d --- /dev/null +++ b/src/test/java/computation/PostfixComputerTest.java @@ -0,0 +1,53 @@ +package computation; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class PostfixComputerTest { + + private final Converter converter = new PostfixConverter(); + private final PostfixComputer postfixComputer = new PostfixComputer(); + + @Test + @DisplayName("기본 사칙 연산 테스트") + void basicCalculationTest() { + String infixExpr = "3 + 4"; + int result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(7); + + infixExpr = "3 - 4"; + result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(-1); + + infixExpr = "3 * 4"; + result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(12); + + infixExpr = "6 / 3"; + result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(2); + } + + @Test + @DisplayName("괄호를 반영한 계산 테스트") + void bracketsTest() { + String infixExpr = "(3 + (4 * 7)) - (6 / 3)"; + int result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(29); + + infixExpr = "3 + (6 / 3)"; + result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(5); + + infixExpr = "9 * (11 + 23)"; + result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(306); + + infixExpr = "(6 + 3) * 4"; + result = postfixComputer.calculate(converter.convert(infixExpr)); + assertThat(result).isEqualTo(36); + } + +} \ No newline at end of file diff --git a/src/test/java/computation/PostfixConverterTest.java b/src/test/java/computation/PostfixConverterTest.java new file mode 100644 index 000000000..cc2c16e9d --- /dev/null +++ b/src/test/java/computation/PostfixConverterTest.java @@ -0,0 +1,33 @@ +package computation; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class PostfixConverterTest { + @Test + @DisplayName("중위표기식을 후위표기식으로 변환") + void convertTest() { + String input = "(3 + (4 * 7)) - (6 / 3)"; + Converter converter = new PostfixConverter(); + List result = converter.convert(input); + assertThat(String.join("", result)).isEqualTo("347*+63/-"); + } + + @Test + @DisplayName("연산자 우선순위 테스트") + void priorityTest() { + String input = "1 + 3 * 6"; + Converter converter = new PostfixConverter(); + List result = converter.convert(input); + assertThat(String.join("", result)).isEqualTo("136*+"); + + input = "1 * (3 + 6)"; + result = converter.convert(input); + assertThat(String.join("", result)).isEqualTo("136+*"); + } + +} \ No newline at end of file diff --git a/src/test/java/repository/CalculatorHistoryRepositoryTest.java b/src/test/java/repository/CalculatorHistoryRepositoryTest.java new file mode 100644 index 000000000..83918cef8 --- /dev/null +++ b/src/test/java/repository/CalculatorHistoryRepositoryTest.java @@ -0,0 +1,19 @@ +package repository; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class CalculatorHistoryRepositoryTest { + + private final CalculatorHistoryRepository repository = new CalculatorHistoryRepository(); + + @Test + @DisplayName("값 저장 및 출력 테스트") + void saveInRepositoryTest() { + repository.save("1+2", 3); + repository.save("1*3", 3); + repository.save("3+(4*8)", 35); + } +} \ No newline at end of file diff --git a/src/test/java/validation/ValidatorTest.java b/src/test/java/validation/ValidatorTest.java new file mode 100644 index 000000000..206713121 --- /dev/null +++ b/src/test/java/validation/ValidatorTest.java @@ -0,0 +1,41 @@ +package validation; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; + +class ValidatorTest { + + @ParameterizedTest + @DisplayName("올바르지 않은 괄호의 쌍 검증 테스트") + @ValueSource(strings = {"((3+4)*2", "(3+4)*2)", "3+2*(2+6", "3)+4*2"}) + void bracketsPairWrongTest(String expression) { + assertThat(Validator.checkBrackets(expression)).isFalse(); + } + + @ParameterizedTest + @DisplayName("올바른 괄호의 쌍 검증 테스트") + @ValueSource(strings = {"(3+4)*2", "3+(4*2)", "(3+2*2+6)", "((3+4)*2)"}) + void bracketsPairTest(String expression) { + assertThat(Validator.checkBrackets(expression)).isTrue(); + } + + @ParameterizedTest + @DisplayName("올바르지 않은 계산식 테스트") + @ValueSource(strings = {"1+", "+1", "1++", "*", "((3+4)", "(3+4))", "3/45+-"}) + void wrongExpressionWrongTest(String expression) { + assertThat(Validator.isRightExpression(expression)).isFalse(); + } + + @ParameterizedTest + @DisplayName("올바른 계산식 테스트") + @ValueSource(strings = {"1+7", "11+1", "121+23", "87*17", "(31+4)", "(3*4)+4", "3+(4*3)"}) + void wrongExpressionTest(String expression) { + assertThat(Validator.isRightExpression(expression)).isTrue(); + } + + +} \ No newline at end of file