diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4b69265 --- /dev/null +++ b/.gitignore @@ -0,0 +1,172 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij,gradle,java +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij,gradle,java + +### 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/intellij,gradle,java diff --git a/README.md b/README.md index a72563c..40c2a05 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,58 @@ # nextstep-coordinate + nextstep 좌표계산기를 OOP와 TDD를 이용하여 구현해보자. + +# 1️⃣ 좌표계산기(선 길이) + +## 기능 요구사항 +- 사용자가 점에 대한 좌표 정보를 입력하는 메뉴를 구성한다. +- 좌표 정보는 괄호"(", ")"로 둘러쌓여 있으며 쉼표(,)로 x값과 y값을 구분한다. +- X, Y좌표 모두 최대 24까지만 입력할 수 있다. +- 입력 범위를 초과할 경우 에러 문구를 출력하고 다시 입력을 받는다. +- 정상적인 좌표값을 입력한 경우, 해당 좌표에 특수문자를 표시한다. +- 좌표값을 두 개 입력한 경우, 두 점을 있는 직선으로 가정한다. 좌표값과 좌표값 사이는 '-' 문자로 구분한다. +- 직선인 경우는 두 점 사이 거리를 계산해서 출력한다. + +### 실행 결과 +``` +좌표를 입력하세요. +(10,10)-(14,15) +``` +``` +두 점 사이 거리는 6.403124 +``` + +# 2️⃣ 좌표계산기(사각형 면적) + +## 기능 요구사항 +- 좌표값을 두 개 입력한 경우, 두 점을 있는 직선으로 가정한다. 좌표값과 좌표값 사이는 '-' 문자로 구분한다. +- 좌표값을 네 개 입력한 경우, 네 점을 연결하는 사각형으로 가정한다. + - 네 점이 뒤틀어진 사다리꼴이나 마름모는 제외하고 직사각형만 허용하도록 검사한다. + - 사각형인 경우 사각형의 넓이를 계산해서 출력한다. + +### 실행 결과 +``` +좌표를 입력하세요. +(10,10)-(22,10)-(22,18)-(10,18) +``` + +``` +사각형 넓이는 96 +``` + +# 3️⃣ 좌표계산(삼각형 면적) + +## 기능 요구사항 +- 좌표값을 두 개 입력한 경우, 두 점을 있는 직선으로 가정한다. 좌표값과 좌표값 사이는 '-' 문자로 구분한다. +- 좌표값을 세 개 입력한 경우, 세 점을 연결하는 삼각형으로 가정한다. + - 삼각형인 경우 삼각형의 넓이를 계산해서 출력한다. + +### 실행 결과 +``` +좌표를 입력하세요. +(10,10)-(14,15)-(20,8) +``` + +``` +삼각형 넓이는 29.0 +``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..086b891 --- /dev/null +++ b/build.gradle @@ -0,0 +1,25 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.1' + id 'io.spring.dependency-management' version '1.1.0' +} + +group = 'com.nextstep' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter' + 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 0000000..c1962a7 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 0000000..37aef8d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..aeb74cb --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/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/HEAD/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + 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 + + +# 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"' + +# 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 0000000..6689b85 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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 0000000..47e8c2b --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'nextstep-coordinate' diff --git a/specification.md b/specification.md new file mode 100644 index 0000000..4e95288 --- /dev/null +++ b/specification.md @@ -0,0 +1,49 @@ +## 기능 요구사항 + +### Coordinate + +- X,Y 좌표를 가진 좌표를 생성한다. +- 좌표를 생성할 때 좌표 범위에 포함되지 않는 경우 예외를 발생시킨다. + +### Coordinates + +- Coordinate를 여러개 가진 일급 컬렉션을 생성한다. +- 문자열을 받아서 파싱하고 리스트에 Coordinate를 생성하여 저장한다. + +### Line + +- 좌표 2개를 받아 선을 만든다.(길이를 측정한다) + +### Square + +- 가로와 세로를 받아서 직사각형을 만든다.(직사각형 넓이를 구한다.) + +### Triangle + +- 3개의 선을 받아서 삼각형을 만든다.(삼각형의 넓이를 구한다.) + +### InputView + +- 사용자의 입력을 받는다. + +### OutputView + +- 좌표를 입력받는 안내메시지를 출력한다. +- 좌표 지도에 입력받은 좌표들을 찍어서 출력한다. +- 두 점 사이의 거리 즉 선의 길이를 출력한다. +- 삼각형의 넓이를 출력한다. +- 사각형의 넓이를 출력한다. + +## 구현 + +### 선 + +![스크린샷 2023-07-05 오후 7 06 02](https://github.com/Hchanghyeon/nextstep-coordinate/assets/92444744/d731a389-5d16-434f-9cdb-31299df7aa98) + +### 사각형 + +![스크린샷 2023-07-05 오후 7 06 20](https://github.com/Hchanghyeon/nextstep-coordinate/assets/92444744/31374d6c-69e0-4f9d-9078-9d0a1cc063fe) + +### 삼각형 + +![스크린샷 2023-07-05 오후 7 06 35](https://github.com/Hchanghyeon/nextstep-coordinate/assets/92444744/04c7d7a6-49e8-4556-87ec-1139ef9bef73) diff --git a/src/main/java/com/nextstep/nextstepcoordinate/Console/InputView.java b/src/main/java/com/nextstep/nextstepcoordinate/Console/InputView.java new file mode 100644 index 0000000..a31c4e3 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/Console/InputView.java @@ -0,0 +1,12 @@ +package com.nextstep.nextstepcoordinate.Console; + +import java.util.Scanner; + +public class InputView { + + private static final Scanner SCANNER = new Scanner(System.in); + + public static String input() { + return SCANNER.nextLine(); + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/Console/OutputView.java b/src/main/java/com/nextstep/nextstepcoordinate/Console/OutputView.java new file mode 100644 index 0000000..909b111 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/Console/OutputView.java @@ -0,0 +1,57 @@ +package com.nextstep.nextstepcoordinate.Console; + +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import java.util.List; + +public class OutputView { + + public static void setCoordinateGuide() { + System.out.println("좌표를 입력해주세요."); + } + + public static void lineLengthGuide(Double lineLength) { + System.out.println("두 점 사이의 거리는 " + lineLength); + } + + public static void squareAreaGuide(Double area) { + System.out.println("사각형의 넓이는 " + area); + } + + public static void triangleAreaGuide(Double area) { + System.out.println("삼각형의 넓이는 " + area); + } + + public static void coordinatePlace(List coordinateList) { + int width = 24; + int height = 24; + + char[][] map = new char[24][24]; + + initMap(width, height, map); + checkMap(coordinateList, map); + coordinateMap(width, height, map); + } + + private static void checkMap(List coordinateList, char[][] map) { + for (Coordinate coordinate : coordinateList) { + map[coordinate.getY() - 1][coordinate.getX() - 1] = '*'; + } + } + + private static void initMap(int width, int height, char[][] map) { + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { + map[i][j] = '.'; + } + } + } + + private static void coordinateMap(int width, int height, char[][] map) { + for (int i = height - 1; i >= 0; i--) { + for (int j = 0; j < width; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/ConsoleApplication.java b/src/main/java/com/nextstep/nextstepcoordinate/ConsoleApplication.java new file mode 100644 index 0000000..3eeadbb --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/ConsoleApplication.java @@ -0,0 +1,51 @@ +package com.nextstep.nextstepcoordinate; + +import com.nextstep.nextstepcoordinate.Console.InputView; +import com.nextstep.nextstepcoordinate.Console.OutputView; +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import com.nextstep.nextstepcoordinate.domain.Coordinates; +import com.nextstep.nextstepcoordinate.domain.Line; +import com.nextstep.nextstepcoordinate.domain.Square; +import com.nextstep.nextstepcoordinate.domain.Triangle; +import java.util.List; + +public class ConsoleApplication { + + private static final int LINE = 2; + private static final int TRIANGLE = 3; + private static final int SQUARE = 4; + + public void run() { + OutputView.setCoordinateGuide(); + Coordinates coordinates = new Coordinates(InputView.input()); + List coordinatesList = coordinates.getCoordinates(); + + if (coordinatesList.size() == LINE) { + OutputView.coordinatePlace(coordinatesList); + Line line = new Line(coordinatesList.get(0), coordinatesList.get(1)); + + OutputView.lineLengthGuide(line.getLineLength()); + } + + if (coordinatesList.size() == TRIANGLE) { + OutputView.coordinatePlace(coordinatesList); + Line a = new Line(coordinatesList.get(0), coordinatesList.get(1)); + Line b = new Line(coordinatesList.get(1), coordinatesList.get(2)); + Line c = new Line(coordinatesList.get(0), coordinatesList.get(2)); + + Triangle triangle = new Triangle(a, b, c); + + OutputView.triangleAreaGuide(triangle.getArea()); + } + + if (coordinatesList.size() == SQUARE) { + OutputView.coordinatePlace(coordinatesList); + Line width = new Line(coordinatesList.get(0), coordinatesList.get(1)); + Line height = new Line(coordinatesList.get(1), coordinatesList.get(2)); + + Square square = new Square(width, height); + + OutputView.squareAreaGuide(square.getArea()); + } + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/CoordinateApplication.java b/src/main/java/com/nextstep/nextstepcoordinate/CoordinateApplication.java new file mode 100644 index 0000000..8a669d3 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/CoordinateApplication.java @@ -0,0 +1,11 @@ +package com.nextstep.nextstepcoordinate; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CoordinateApplication { + + public static void main(String[] args) { + new ConsoleApplication().run(); + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/domain/Coordinate.java b/src/main/java/com/nextstep/nextstepcoordinate/domain/Coordinate.java new file mode 100644 index 0000000..8d40125 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/domain/Coordinate.java @@ -0,0 +1,36 @@ +package com.nextstep.nextstepcoordinate.domain; + +import java.text.MessageFormat; + +public class Coordinate { + + private final static int COORDINATE_MAX = 24; + private final static int COORDINATE_MIN = 0; + + private int x; + private int y; + + public Coordinate(int x, int y) { + validateCoordinateRange(x, y); + this.x = x; + this.y = y; + } + + private void validateCoordinateRange(int x, int y) { + if (COORDINATE_MIN > x || x > COORDINATE_MAX) { + throw new IllegalArgumentException(MessageFormat.format("입력하신 X좌표 {0}는 입력값의 범위에 포함되지 않습니다.", x)); + } + + if (COORDINATE_MIN > y || y > COORDINATE_MAX) { + throw new IllegalArgumentException(MessageFormat.format("입력하신 Y좌표 {0}는 입력값의 범위에 포함되지 않습니다.", y)); + } + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/domain/Coordinates.java b/src/main/java/com/nextstep/nextstepcoordinate/domain/Coordinates.java new file mode 100644 index 0000000..8d0ef50 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/domain/Coordinates.java @@ -0,0 +1,28 @@ +package com.nextstep.nextstepcoordinate.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Coordinates { + + private List coordinates = new ArrayList<>(); + + public Coordinates(String inputCoordinates) { + parseCoordinates(inputCoordinates); + this.coordinates = coordinates; + } + + private void parseCoordinates(String inputCoordinates) { + String[] splitedCoordinates = inputCoordinates.split("-"); + + for (int i = 0; i < splitedCoordinates.length; i++) { + String[] splitedCoordinate = splitedCoordinates[i].replaceAll("[()]", "").split(","); + Coordinate coordinate = new Coordinate(Integer.parseInt(splitedCoordinate[0]), Integer.parseInt(splitedCoordinate[1])); + coordinates.add(coordinate); + } + } + + public List getCoordinates() { + return coordinates; + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/domain/Line.java b/src/main/java/com/nextstep/nextstepcoordinate/domain/Line.java new file mode 100644 index 0000000..5c620c3 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/domain/Line.java @@ -0,0 +1,14 @@ +package com.nextstep.nextstepcoordinate.domain; + +public class Line { + + private double lineLength; + + public Line(Coordinate coordinate1, Coordinate coordinate2) { + this.lineLength = Math.sqrt(Math.pow((coordinate1.getX() - coordinate2.getX()), 2) + Math.pow((coordinate1.getY()) - coordinate2.getY(), 2)); + } + + public double getLineLength() { + return lineLength; + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/domain/Square.java b/src/main/java/com/nextstep/nextstepcoordinate/domain/Square.java new file mode 100644 index 0000000..2aa8681 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/domain/Square.java @@ -0,0 +1,14 @@ +package com.nextstep.nextstepcoordinate.domain; + +public class Square { + + private double area; + + public Square(Line width, Line height) { + area = width.getLineLength() * height.getLineLength(); + } + + public double getArea() { + return area; + } +} diff --git a/src/main/java/com/nextstep/nextstepcoordinate/domain/Triangle.java b/src/main/java/com/nextstep/nextstepcoordinate/domain/Triangle.java new file mode 100644 index 0000000..0bc60a4 --- /dev/null +++ b/src/main/java/com/nextstep/nextstepcoordinate/domain/Triangle.java @@ -0,0 +1,18 @@ +package com.nextstep.nextstepcoordinate.domain; + +public class Triangle { + + private Double area; + + public Triangle(Line a, Line b, Line c) { + double aLength = a.getLineLength(); + double bLength = b.getLineLength(); + double cLength = c.getLineLength(); + double s = (aLength + bLength + cLength) / 2; + this.area = Math.sqrt(s * (s - aLength) * (s - bLength) * (s - cLength)); + } + + public Double getArea() { + return area; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/src/test/java/com/nextstep/nextstepcoordinate/CoordinateTest.java b/src/test/java/com/nextstep/nextstepcoordinate/CoordinateTest.java new file mode 100644 index 0000000..350c8a7 --- /dev/null +++ b/src/test/java/com/nextstep/nextstepcoordinate/CoordinateTest.java @@ -0,0 +1,38 @@ +package com.nextstep.nextstepcoordinate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class CoordinateTest { + + @Test + @DisplayName("좌표를 생성한다.") + void createCoordinate() { + // given + Coordinate coordinate = new Coordinate(10, 23); + + // when & then + assertThat(coordinate.getX()).isEqualTo(10); + assertThat(coordinate.getY()).isEqualTo(23); + } + + + @Test + @DisplayName("좌표의 생성할 때 범위를 넘어서면 에외를 발생시킨다") + void excpetionCoordinate() { + // given & when & then + assertThatThrownBy(() -> new Coordinate(25, 10)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("입력하신 X좌표 25는 입력값의 범위에 포함되지 않습니다."); + + // given & when & then + assertThatThrownBy(() -> new Coordinate(14, -3)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("입력하신 Y좌표 -3는 입력값의 범위에 포함되지 않습니다."); + } + +} diff --git a/src/test/java/com/nextstep/nextstepcoordinate/CoordinatesTest.java b/src/test/java/com/nextstep/nextstepcoordinate/CoordinatesTest.java new file mode 100644 index 0000000..e6b0c0f --- /dev/null +++ b/src/test/java/com/nextstep/nextstepcoordinate/CoordinatesTest.java @@ -0,0 +1,27 @@ +package com.nextstep.nextstepcoordinate; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import com.nextstep.nextstepcoordinate.domain.Coordinates; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class CoordinatesTest { + + @Test + @DisplayName("좌표를 담은 좌표 리스트를 생성한다.") + void createCoordinates() { + // given + Coordinates coordinates = new Coordinates("(10,10)-(14,15)"); + Coordinate coordinate1 = new Coordinate(10, 10); + Coordinate coordinate2 = new Coordinate(14, 15); + List coordinateList = coordinates.getCoordinates(); + + // when & then + assertThat(coordinateList.get(0)).usingRecursiveComparison().isEqualTo(coordinate1); + assertThat(coordinateList.get(1)).usingRecursiveComparison().isEqualTo(coordinate2); + } + +} diff --git a/src/test/java/com/nextstep/nextstepcoordinate/LineTest.java b/src/test/java/com/nextstep/nextstepcoordinate/LineTest.java new file mode 100644 index 0000000..fc9dec6 --- /dev/null +++ b/src/test/java/com/nextstep/nextstepcoordinate/LineTest.java @@ -0,0 +1,24 @@ +package com.nextstep.nextstepcoordinate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; + +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import com.nextstep.nextstepcoordinate.domain.Line; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class LineTest { + + @Test + @DisplayName("두 점 사이의 선 거리를 계산한다.") + void calculateLine() { + // given + Coordinate coordinate1 = new Coordinate(10, 10); + Coordinate coordinate2 = new Coordinate(14, 15); + Line line = new Line(coordinate1, coordinate2); + + // when && then + assertThat(line.getLineLength()).isEqualTo(6.403124, offset(0.00099)); + } +} diff --git a/src/test/java/com/nextstep/nextstepcoordinate/SquareTest.java b/src/test/java/com/nextstep/nextstepcoordinate/SquareTest.java new file mode 100644 index 0000000..5b51ffa --- /dev/null +++ b/src/test/java/com/nextstep/nextstepcoordinate/SquareTest.java @@ -0,0 +1,30 @@ +package com.nextstep.nextstepcoordinate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; + +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import com.nextstep.nextstepcoordinate.domain.Line; +import com.nextstep.nextstepcoordinate.domain.Square; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class SquareTest { + + @Test + @DisplayName("사각형의 넓이를 구한다.") + void calculateArea() { + // given + Coordinate coordinate1 = new Coordinate(10, 10); + Coordinate coordinate2 = new Coordinate(22, 10); + Coordinate coordinate3 = new Coordinate(22, 18); + + Line width = new Line(coordinate1, coordinate2); + Line height = new Line(coordinate2, coordinate3); + + Square square = new Square(width, height); + + // when && then + assertThat(square.getArea()).isEqualTo(96, offset(0.00099)); + } +} diff --git a/src/test/java/com/nextstep/nextstepcoordinate/TriangleTest.java b/src/test/java/com/nextstep/nextstepcoordinate/TriangleTest.java new file mode 100644 index 0000000..0e20bf7 --- /dev/null +++ b/src/test/java/com/nextstep/nextstepcoordinate/TriangleTest.java @@ -0,0 +1,31 @@ +package com.nextstep.nextstepcoordinate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; + +import com.nextstep.nextstepcoordinate.domain.Coordinate; +import com.nextstep.nextstepcoordinate.domain.Line; +import com.nextstep.nextstepcoordinate.domain.Triangle; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class TriangleTest { + + @Test + @DisplayName("삼각형의 넓이를 구한다.") + void calculateArea() { + // given + Coordinate coordinate1 = new Coordinate(10, 10); + Coordinate coordinate2 = new Coordinate(14, 15); + Coordinate coordinate3 = new Coordinate(20, 8); + + Line a = new Line(coordinate1, coordinate2); + Line b = new Line(coordinate2, coordinate3); + Line c = new Line(coordinate1, coordinate3); + + Triangle triangle = new Triangle(a, b, c); + + // when && then + assertThat(triangle.getArea()).isEqualTo(29, offset(0.00099)); + } +}