diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..c2065bc26 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..e62a0b31e --- /dev/null +++ b/build.gradle @@ -0,0 +1,24 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.0' + id 'io.spring.dependency-management' version '1.1.0' +} + +group = 'com.bona' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter' + compileOnly 'org.projectlombok:lombok:1.18.26' + annotationProcessor 'org.projectlombok:lombok:1.18.26' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} 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..774fae876 --- /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.6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 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..53a6b238d --- /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..3cbb6cb5f --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'java-calculator' diff --git a/src/main/java/com/bona/javacalculator/Main.java b/src/main/java/com/bona/javacalculator/Main.java new file mode 100644 index 000000000..fd46af675 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/Main.java @@ -0,0 +1,28 @@ +package com.bona.javacalculator; + +import com.bona.javacalculator.core.calculator.Calculator; +import com.bona.javacalculator.io.Console; +import com.bona.javacalculator.core.CalculatorManager; +import com.bona.javacalculator.core.converter.Converter; +import com.bona.javacalculator.core.converter.PostfixConverter; +import com.bona.javacalculator.repository.CalMemoryRepository; +import com.bona.javacalculator.repository.MemoryRepository; +import com.bona.javacalculator.util.Validator; + +public class Main { + + public static void main(String[] args) { + MemoryRepository repository = new CalMemoryRepository(); + Console console = new Console(); + Converter converter = new PostfixConverter(); + Validator validator = new Validator(); + Calculator calculator = new Calculator(); + + CalculatorManager calculatorManager = new CalculatorManager(calculator, repository, console, converter, validator); + + + calculatorManager.run(); + + } + +} diff --git a/src/main/java/com/bona/javacalculator/core/CalculatorManager.java b/src/main/java/com/bona/javacalculator/core/CalculatorManager.java new file mode 100644 index 000000000..015987c08 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/CalculatorManager.java @@ -0,0 +1,76 @@ +package com.bona.javacalculator.core; + +import com.bona.javacalculator.core.calculator.Calculator; +import com.bona.javacalculator.core.converter.Converter; +import com.bona.javacalculator.io.Console; +import com.bona.javacalculator.model.ExpressionResult; +import com.bona.javacalculator.repository.MemoryRepository; +import com.bona.javacalculator.util.Validator; + +import java.util.List; + +public class CalculatorManager { + + private final Converter converter; + private final Validator validator; + private final MemoryRepository repository; + private final Console console; + private final Calculator calculator; + + public CalculatorManager(Calculator calculator, MemoryRepository repository, Console console,Converter converter, Validator validator) { + this.repository = repository; + this.console = console; + this.converter = converter; + this.validator = validator; + this.calculator = calculator; + } + + public void run() { + boolean isRun = true; + + while (isRun) { + try { + String input = console.input("1. 조회 2. 계산 3.종료"); + + Option option = Option.of(input); + + switch (option) { + case INQUIRY -> inquiry(); + case CALCULATE -> calculate(); + case EXIT -> isRun = false; + default -> { + } + } + } catch (RuntimeException e) { + console.printMessage(e.getMessage()); + } + } + } + + + public void calculate() { + String formula = console.input("식을 입력해주세요 : "); + + validator.validateFormula(formula); + + List postfix = converter.convert(formula); + double result = calculator.calculate(postfix); + + repository.save(new ExpressionResult(formula, result)); + + console.outAnswer(result); + } + + + public void inquiry() { + List all = repository.findAll(); + + if (all.isEmpty()) { + console.printMessage("조회 결과 기록이 존재하지 않습니다"); + return; + } + + console.printAll(all); + } + +} diff --git a/src/main/java/com/bona/javacalculator/core/Operator.java b/src/main/java/com/bona/javacalculator/core/Operator.java new file mode 100644 index 000000000..9b0268091 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/Operator.java @@ -0,0 +1,36 @@ +package com.bona.javacalculator.core; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Operator { + PLUS("+", (num1, num2) -> num1 + num2), + MINUS("-", (num1, num2) -> num1 - num2), + MULTIPLY("*", (num1, num2) -> num1 * num2), + DIVIDE("/", (num1, num2) -> num1 / num2); + + private final String operator; + private final BiFunction expression; + + Operator(String operator, BiFunction expression) { + this.operator = operator; + this.expression = expression; + } + + public static double calculate(String operator, double num1, double num2) { + return getOperator(operator).expression.apply(num1, num2); + } + + private static Operator getOperator(String operator) { + return Arrays.stream(values()) + .filter(o -> o.operator.equals(operator)) + .findFirst().orElseThrow(() -> new IllegalArgumentException("올바른 연산자가 아닙니다.")); + } + + public static boolean isOperator(String unCheckedOperator) { + return Arrays.stream(Operator.values()) + .anyMatch(operators -> operators.operator.equals(unCheckedOperator)); + } + + +} diff --git a/src/main/java/com/bona/javacalculator/core/Option.java b/src/main/java/com/bona/javacalculator/core/Option.java new file mode 100644 index 000000000..007838dab --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/Option.java @@ -0,0 +1,25 @@ +package com.bona.javacalculator.core; + + +public enum Option { + EXIT(3), INQUIRY(1), CALCULATE(2); + + private int matchNum; + + Option(int matchNum) { + this.matchNum = matchNum; + } + + + public static Option of(String input) { + + for (Option value : values()) { + if (value.matchNum == Integer.parseInt(input)) { + return value; + } + } + + throw new RuntimeException("입력이 잘못되었습니다."); + } + +} diff --git a/src/main/java/com/bona/javacalculator/core/Priority.java b/src/main/java/com/bona/javacalculator/core/Priority.java new file mode 100644 index 000000000..488d846a7 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/Priority.java @@ -0,0 +1,29 @@ +package com.bona.javacalculator.core; + +public class Priority { + + public static int getOperationPriority(String operator) { + + switch (operator) { + case "*": + case "/": + return 2; + case "+": + case "-": + return 1; + default: + throw new IllegalStateException("유효하지 않은 연산자 입니다" + operator); + } + } + + //연산자 우선순위 비교 + public static int compareOperation(String operator, String NowOperator) { + int operationPriority = getOperationPriority(operator); + + int operationPriorityNow = getOperationPriority(NowOperator); + + return Integer.compare(operationPriorityNow, operationPriority); + + } + +} diff --git a/src/main/java/com/bona/javacalculator/core/calculator/AbstractCalculator.java b/src/main/java/com/bona/javacalculator/core/calculator/AbstractCalculator.java new file mode 100644 index 000000000..60839a75e --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/calculator/AbstractCalculator.java @@ -0,0 +1,9 @@ +package com.bona.javacalculator.core.calculator; + +import java.util.List; + +public interface AbstractCalculator { + + double calculate(List formula); + +} diff --git a/src/main/java/com/bona/javacalculator/core/calculator/Calculator.java b/src/main/java/com/bona/javacalculator/core/calculator/Calculator.java new file mode 100644 index 000000000..2ff1c49e6 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/calculator/Calculator.java @@ -0,0 +1,38 @@ +package com.bona.javacalculator.core.calculator; + +import com.bona.javacalculator.core.*; +import com.bona.javacalculator.util.Validator; + +import java.util.List; +import java.util.Stack; + +public class Calculator implements AbstractCalculator{ + + + @Override + public double calculate(List formula) { + + Stack numbers = new Stack<>(); + + String split; + + double num1 = 0; + double num2 = 0; + + for (int i = 0; i < formula.size(); i++) { + + split = formula.get(i); + + if (Validator.isNumber(split)) { + numbers.push(Double.valueOf(split)); + } else { + num2 = numbers.pop(); + num1 = numbers.pop(); + + numbers.push(Operator.calculate(split, num1, num2)); + } + } + return numbers.pop(); + } + +} diff --git a/src/main/java/com/bona/javacalculator/core/converter/Converter.java b/src/main/java/com/bona/javacalculator/core/converter/Converter.java new file mode 100644 index 000000000..a567ade8b --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/converter/Converter.java @@ -0,0 +1,7 @@ +package com.bona.javacalculator.core.converter; + +import java.util.List; + +public interface Converter { + List convert(String input); +} diff --git a/src/main/java/com/bona/javacalculator/core/converter/PostfixConverter.java b/src/main/java/com/bona/javacalculator/core/converter/PostfixConverter.java new file mode 100644 index 000000000..927f5e553 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/core/converter/PostfixConverter.java @@ -0,0 +1,58 @@ +package com.bona.javacalculator.core.converter; + +import com.bona.javacalculator.core.Operator; +import com.bona.javacalculator.core.Priority; +import com.bona.javacalculator.util.Validator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class PostfixConverter implements Converter { + private final String WHITE_SPACE = ""; + private final Priority priorityFind = new Priority(); + + @Override + public List convert(String input) { + List postfix = new ArrayList<>(); + String[] splitInput = input.split(WHITE_SPACE); + + Stack stack = new Stack<>(); + + for (int index = 0; index < splitInput.length; index++) { + String pieceInput = splitInput[index]; + if (Operator.isOperator(pieceInput)) { + pushOperator(pieceInput, postfix, stack); + } else { + pushNumber(pieceInput, postfix); + } + } + while (!stack.isEmpty()) { + postfix.add(stack.pop()); + } + return postfix; + + } + + public void pushOperator(String operator, List postfix, Stack operatorStack) { + if (operatorStack.isEmpty() || Priority.compareOperation(operatorStack.peek(), operator) > 0) { + operatorStack.push(operator); + return; + } + while (!operatorStack.isEmpty() && Priority.compareOperation(operatorStack.peek(), operator) <= 0) { + postfix.add(operatorStack.pop()); + } + operatorStack.push(operator); + } + + + public void pushNumber(String number, List postfix) { + if (!Validator.isNumber(number)) { + throw new NumberFormatException(); + } + postfix.add(number); + } + + +} + diff --git a/src/main/java/com/bona/javacalculator/io/Console.java b/src/main/java/com/bona/javacalculator/io/Console.java new file mode 100644 index 000000000..d0bfb757b --- /dev/null +++ b/src/main/java/com/bona/javacalculator/io/Console.java @@ -0,0 +1,53 @@ +package com.bona.javacalculator.io; + +import com.bona.javacalculator.model.ExpressionResult; +import com.bona.javacalculator.util.Validator; + +import java.util.List; +import java.util.Scanner; + +public class Console implements Input, Output { + + private final Scanner scanner = new Scanner(System.in); + + + @Override + public String input(String input) { + System.out.println(input); + return scanner.nextLine(); + } + + + @Override + public void outAnswer(Double answer) { + boolean isLong = Validator.isLong(answer); + if (isLong) { + Long changeAnswer = answer.longValue(); + System.out.println(changeAnswer); + } else { + System.out.println(answer); + } + } + + @Override + public void printAll(List expressionResultList) { + for (ExpressionResult history : expressionResultList) { + String input = history.getInput(); + Double answer = history.getAnswer(); + + System.out.print(input + "="); + boolean isLong = Validator.isLong(answer); + if (isLong) { + Long changeAnswer = answer.longValue(); + System.out.println(changeAnswer); + } else { + System.out.println(answer); + } + } + } + + @Override + public void printMessage(String message) { + System.out.println(message); + } +} diff --git a/src/main/java/com/bona/javacalculator/io/Input.java b/src/main/java/com/bona/javacalculator/io/Input.java new file mode 100644 index 000000000..33b8ac069 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/io/Input.java @@ -0,0 +1,6 @@ +package com.bona.javacalculator.io; + +public interface Input { + String input(String S); + +} diff --git a/src/main/java/com/bona/javacalculator/io/Output.java b/src/main/java/com/bona/javacalculator/io/Output.java new file mode 100644 index 000000000..1b9d6ad3a --- /dev/null +++ b/src/main/java/com/bona/javacalculator/io/Output.java @@ -0,0 +1,13 @@ +package com.bona.javacalculator.io; + +import com.bona.javacalculator.model.ExpressionResult; + +import java.util.List; + +public interface Output { + void outAnswer(Double answer); + + void printAll(List expressionResultList); + + void printMessage(String message); +} diff --git a/src/main/java/com/bona/javacalculator/model/ExpressionResult.java b/src/main/java/com/bona/javacalculator/model/ExpressionResult.java new file mode 100644 index 000000000..e8cfbb393 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/model/ExpressionResult.java @@ -0,0 +1,33 @@ +package com.bona.javacalculator.model; + +public class ExpressionResult { + private Long id; + private String input; + private Double answer; + + public ExpressionResult(String input, Double answer) { + this.input = input; + this.answer = answer; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getInput() { + return input; + } + + public void setInput(String input) { + this.input = input; + } + + public Double getAnswer() { + return answer; + } + +} diff --git a/src/main/java/com/bona/javacalculator/repository/CalMemoryRepository.java b/src/main/java/com/bona/javacalculator/repository/CalMemoryRepository.java new file mode 100644 index 000000000..a5303378f --- /dev/null +++ b/src/main/java/com/bona/javacalculator/repository/CalMemoryRepository.java @@ -0,0 +1,38 @@ +package com.bona.javacalculator.repository; + +import com.bona.javacalculator.model.ExpressionResult; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Repository +public class CalMemoryRepository implements MemoryRepository { + + private static final Map store = new HashMap<>(); + + private static long sequence = 0L; + + @Override + public ExpressionResult save(ExpressionResult expressionResult) { + + expressionResult.setId(++sequence); + + store.put(expressionResult.getId(), expressionResult); + + return expressionResult; + } + + @Override + public ExpressionResult findById(Long id) { + return store.get(id); + } + + @Override + public List findAll() { + return new ArrayList<>(store.values()); + } + +} diff --git a/src/main/java/com/bona/javacalculator/repository/MemoryRepository.java b/src/main/java/com/bona/javacalculator/repository/MemoryRepository.java new file mode 100644 index 000000000..dc6ad21f1 --- /dev/null +++ b/src/main/java/com/bona/javacalculator/repository/MemoryRepository.java @@ -0,0 +1,18 @@ +package com.bona.javacalculator.repository; + +import com.bona.javacalculator.model.ExpressionResult; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface MemoryRepository { + + ExpressionResult save(ExpressionResult expressionResult); + + ExpressionResult findById(Long id); + + List findAll(); + + +} diff --git a/src/main/java/com/bona/javacalculator/util/Validator.java b/src/main/java/com/bona/javacalculator/util/Validator.java new file mode 100644 index 000000000..e0301e48e --- /dev/null +++ b/src/main/java/com/bona/javacalculator/util/Validator.java @@ -0,0 +1,86 @@ +package com.bona.javacalculator.util; + +import com.bona.javacalculator.io.Console; +import com.bona.javacalculator.core.Operator; + + +public class Validator { + + private final Console console = new Console(); + + public void validateFormula(String input) { + validateIsEmpty(input); + validateWithDivideZero(input); + validateFomat(input); + } + + private void validateFomat(String input) { + String[] inputString = input.split(""); + + if (inputString.length < 3) { + throw new RuntimeException("입력식이 포맷에 맞지 않습니다."); + } + + if (!isNumber(inputString[inputString.length - 1])) { + throw new RuntimeException("입력식이 포맷에 맞지 않습니다."); + } + for (int i = 0; i < inputString.length; i++) { + if (i % 2 == 1) { + if (!Operator.isOperator(inputString[i])) { + throw new RuntimeException("입력식이 포맷에 맞지 않습니다."); + } + } + } + } + + private void validateWithDivideZero(String input) { + String[] inputString = input.split(""); + + boolean isDivision = false; + for (int i = 0; i < inputString.length; i++) { + + if (i % 2 == 1) { + if (inputString[i].equals("/")) { + isDivision = true; + } + + } else if (!isValidNumber(inputString[i], isDivision)) { + throw new ArithmeticException("0으로 나눌 수 없습니다."); + } + } + } + + private void validateIsEmpty(String input) { + if (input.isEmpty()) { + throw new RuntimeException("입력 값이 비어있습니다."); + } + } + + + private boolean isValidNumber(String input, boolean isDivision) { + + if (!isNumber(input)) { + return false; + } + + if (input.equals("0") && isDivision) { + return false; + } + return true; + } + + public static boolean isNumber(String input) { + for (int i = 0; i < input.length(); i++) { + if (!Character.isDigit(input.charAt(i))) { + return false; + } + } + return true; + } + + + public static boolean isLong(double num) { + return num == (long) num; + } + +} diff --git a/src/test/java/com/bona/javacalculator/JavaCalculatorApplicationTests.java b/src/test/java/com/bona/javacalculator/JavaCalculatorApplicationTests.java new file mode 100644 index 000000000..525269307 --- /dev/null +++ b/src/test/java/com/bona/javacalculator/JavaCalculatorApplicationTests.java @@ -0,0 +1,13 @@ +package com.bona.javacalculator; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class JavaCalculatorApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/bona/javacalculator/core/CalculateTest.java b/src/test/java/com/bona/javacalculator/core/CalculateTest.java new file mode 100644 index 000000000..6c602330e --- /dev/null +++ b/src/test/java/com/bona/javacalculator/core/CalculateTest.java @@ -0,0 +1,30 @@ +package com.bona.javacalculator.kernel; + +import com.bona.javacalculator.core.calculator.Calculator; +import com.bona.javacalculator.core.converter.PostfixConverter; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +class CalculateTest { + + Calculator calculator = new Calculator(); + PostfixConverter makePostfix = new PostfixConverter(); + + @Test + @DisplayName("결과값 반환 테스트") + public void resultTest() { + //given + String input = "1+2*3"; + + //when + List convert = makePostfix.convert(input); + Double result = calculator.calculate(convert); + + //then + Assertions.assertThat(result).isEqualTo(7); + } + +} \ No newline at end of file diff --git a/src/test/java/com/bona/javacalculator/core/PostfixTest.java b/src/test/java/com/bona/javacalculator/core/PostfixTest.java new file mode 100644 index 000000000..3b18243fe --- /dev/null +++ b/src/test/java/com/bona/javacalculator/core/PostfixTest.java @@ -0,0 +1,27 @@ +package com.bona.javacalculator.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.bona.javacalculator.core.converter.PostfixConverter; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +class PostfixTest { + + PostfixConverter makePostfix = new PostfixConverter(); + + @Test + @DisplayName("후위표기식 출력 테스트") + public void makePostfixTest() { + //given + String input = "1+2*3"; + String wantInput = "123*+"; + //when + List convert = makePostfix.convert(input); + //then + assertThat(convert).isEqualTo(wantInput); + } + +} \ No newline at end of file diff --git a/src/test/java/com/bona/javacalculator/core/ValidatorTest.java b/src/test/java/com/bona/javacalculator/core/ValidatorTest.java new file mode 100644 index 000000000..863e95f7c --- /dev/null +++ b/src/test/java/com/bona/javacalculator/core/ValidatorTest.java @@ -0,0 +1,70 @@ +package com.bona.javacalculator.core; + +import com.bona.javacalculator.util.Validator; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +class ValidatorTest { + + Validator validator = new Validator(); + + @Test + @DisplayName("0으로 나눌때 runtime exception 반환 테스트") + public void divisionByZero() { + //given + String input = "1/0"; + //when + Throwable exception = assertThrows(RuntimeException.class, () -> { + validator.validateFormula(input); + }); + //then + assertEquals("0으로 나눌 수 없습니다.", exception.getMessage()); + + } + + @Test + @DisplayName("공백이 있는 연산식 테스트") + public void whiteSpaceInput() { + //given + String input = ""; + //when + Throwable exception = assertThrows(RuntimeException.class, () -> { + validator.validateFormula(input); + }); + //then + assertEquals("입력 값이 비어있습니다.", exception.getMessage()); + + } + + @Test + @DisplayName("올바른 format이 아닌 연산식 테스트") + public void invalidFormatInput() { + //given + String input = "1+3-"; + //when + Throwable exception = assertThrows(RuntimeException.class, () -> { + validator.validateFormula(input); + }); + //then + assertEquals("입력식이 포맷에 맞지 않습니다.", exception.getMessage()); + + } + + @Test + @DisplayName("연산자 자리에 다른 문자가 있는 연산식 테스트") + public void notOperatorInput() { + //given + String input = "1+3=1"; + //when + Throwable exception = assertThrows(RuntimeException.class, () -> { + validator.validateFormula(input); + }); + //then + assertEquals("입력식이 포맷에 맞지 않습니다.", exception.getMessage()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/bona/javacalculator/repository/CalMemoryRepositoryTest.java b/src/test/java/com/bona/javacalculator/repository/CalMemoryRepositoryTest.java new file mode 100644 index 000000000..80085c25a --- /dev/null +++ b/src/test/java/com/bona/javacalculator/repository/CalMemoryRepositoryTest.java @@ -0,0 +1,27 @@ +package com.bona.javacalculator.repository; + +import com.bona.javacalculator.model.ExpressionResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class CalMemoryRepositoryTest { + MemoryRepository memoryRepository = new CalMemoryRepository(); + + @DisplayName("저장 테스트") + @Test + void save() { + //given + ExpressionResult expressionResult = new ExpressionResult("1+2",3.0); + + //when + ExpressionResult savedExpressionResult = memoryRepository.save(expressionResult); + + //then + ExpressionResult findExpressionResult = memoryRepository.findById(expressionResult.getId()); + assertThat(findExpressionResult).isEqualTo(savedExpressionResult); + } + +} \ No newline at end of file