Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import calculator.Calculator;
import calculator.CalculatorFactory;
import domain.Coordinate;
import view.InputView;
import view.OutputView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) throws IOException {
InputView inputView = new InputView();
OutputView outputView = new OutputView();
List<Coordinate> coordinateList = new ArrayList<>();
double result = 0;
CalculatorFactory calculatorFactory = new CalculatorFactory(coordinateList,result);

while (result==0){
try {
String[] inputArray = inputView.creatCoordinate();
Calculator calculator = calculatorFactory.calculateFactory(inputArray);
result = calculator.calculator();
System.out.println(outputView.resultOutput(calculator,result));
}catch (IOException e){
System.out.println(e.getMessage());
coordinateList.clear();
}
}

}
}
11 changes: 11 additions & 0 deletions src/main/java/calculator/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package calculator;

import java.io.IOException;

public interface Calculator {

double calculator() throws IOException;

int getCoordinateCount();

}
41 changes: 41 additions & 0 deletions src/main/java/calculator/CalculatorFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package calculator;

import domain.Coordinate;

import java.io.IOException;
import java.util.List;

public class CalculatorFactory {
private List<Coordinate> coordinateList;
private double result;
Copy link

@deok-beom deok-beom Oct 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result는 어디에 쓰이는 값인가요? 🧑‍🦲

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

부끄럽지만 안쓰입니다.. ㅠ.. 코드를 수정하면서 다른건 다 뺐는데 CalculatorFactory에 하나 남아있었네요..ㅠㅠ



public CalculatorFactory(List<Coordinate> coordinateList,double result) {
this.coordinateList = coordinateList;
this.result = result;
}

public Calculator calculateFactory(String[] splitInput) throws IOException {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

입력에 따라 다른 Caculator를 생성하는 메소드라면 createCalculator나 getCalculator 같은 메소드 이름이 더 알아보기 쉬울 것 같습니다.

coordinateList = addCoordinate(splitInput);

if(coordinateList.size() == 2){
return new CoordinateLengthCalculator(coordinateList);
}
if(coordinateList.size() == 3){
return new TriangleCalculator(coordinateList);
}
if(coordinateList.size() == 4){
return new SquareCalculator(coordinateList);
}
return null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

null을 리턴하는 것 외에 다른 방법을 써보면 어떨까요?

  1. 디폴트로 리턴하는 녀석을 지정하거나 (if를 아무것도 안 탈 시 리턴할 녀석)
  2. 예외를 던지는 방법

정도가 있을 것 같습니다!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오.. 안그래도 null로 리턴 시킬 경우에 NullPointerException이 걱정되었는데 아예 예외를 던지는것도 좋은 방법인것 같습니다.

}

private List<Coordinate> addCoordinate(String[] splitInput) throws IOException {
for (String originalCoordinate:splitInput) {
Coordinate coordinate = new Coordinate(originalCoordinate);
coordinateList.add(coordinate);
}
return coordinateList;
}

}
29 changes: 29 additions & 0 deletions src/main/java/calculator/CoordinateLengthCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package calculator;

import domain.Coordinate;

import java.io.IOException;
import java.util.List;

public class CoordinateLengthCalculator implements Calculator{
private final List<Coordinate> coordinateList;

public CoordinateLengthCalculator(List<Coordinate> coordinateList) {
this.coordinateList = coordinateList;
}

@Override
public double calculator() {
int x = Math.abs(coordinateList.get(0).getX() - coordinateList.get(1).getX());
int y = Math.abs(coordinateList.get(0).getY() - coordinateList.get(1).getY());
double somPow = Math.pow(x, 2) + Math.pow(y, 2);
return Math.sqrt(somPow);
}

@Override
public int getCoordinateCount() {
return coordinateList.size();
}


}
88 changes: 88 additions & 0 deletions src/main/java/calculator/SquareCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package calculator;

import domain.Coordinate;

import java.io.IOException;
import java.util.List;

public class SquareCalculator implements Calculator{
private final List<Coordinate> coordinateList;

public SquareCalculator(List<Coordinate> coordinateList) {
this.coordinateList = coordinateList;
}

@Override
public double calculator() throws IOException {
System.out.println("사각형 넓이 구하기");
//삐뚤어진 사각형인지 아닌지 먼저 검증
validateSquare();
//가로길이 구하기
double width = calculateWidth(coordinateList);
//세로길이 구하기
double height = calculateHeight(coordinateList);
//넓이 계산하기
return width * height;
}
Comment on lines +16 to +26
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아주 세세한 예외로직 멋집니다 ㅎㅎ 더불어서 매소드로 나누어주셔서 읽기 편하네요!


private void validateSquare() throws IOException {
//꼭지점 A(x,y), B(x,y),C(x,y),D(x,y)
//정사각형 또는 직사각형은 x가 두개가 같고 y가 두개가 같다.
int referenceX = coordinateList.get(0).getX();
int referenceY = coordinateList.get(0).getY();
int count = 0;

for (int i = 1; i < coordinateList.size(); i++) {
if(coordinateList.get(i).getX()==referenceX &&coordinateList.get(i).getY() == referenceY){
throw new IOException("정사각형 또는 직사각형의 좌표를 입력해주세요.");
}
if(coordinateList.get(i).getX()==referenceX || coordinateList.get(i).getY() == referenceY){
count++;
}
}

if (!(count ==2)){
throw new IOException("정사각형 또는 직사각형의 좌표를 입력해주세요.");
}

}

@Override
public int getCoordinateCount() {
return coordinateList.size();
}

private double calculateWidth(List<Coordinate> coordinateList){
//y좌표가 같은것끼리 찾아서 ax-bx를 하면 가로길이 나옴.
Coordinate aCoordinate;
Coordinate bCoordinate = null;

aCoordinate = coordinateList.get(0);

for (int i = 1; i < coordinateList.size(); i++) {
if(aCoordinate.getY()==coordinateList.get(i).getY()){
bCoordinate = coordinateList.get(i);
break;
}
}

return Math.abs(aCoordinate.getX()-bCoordinate.getX());
}

private double calculateHeight(List<Coordinate> coordinateList){
//x좌표가 같은것끼리 찾아서 ay-by를 하면 세로길이 나옴.
Coordinate aCoordinate = null;
Coordinate bCoordinate = null;

aCoordinate = coordinateList.get(0);

for (int i = 1; i < coordinateList.size(); i++) {
if(aCoordinate.getX()==coordinateList.get(i).getX()){
bCoordinate = coordinateList.get(i);
break;
}
}

return Math.abs(aCoordinate.getY()-bCoordinate.getY());
}
}
Comment on lines +55 to +88
Copy link
Collaborator

@ca1af ca1af Oct 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 매서드들을 하나로 합칠 수 있는 방법은 없을까요?

Coordinate aCoordinate = null;

이부분에서 null로 초기화를 한 이유가 궁금합니다!

41 changes: 41 additions & 0 deletions src/main/java/calculator/TriangleCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package calculator;

import domain.Coordinate;

import java.util.List;

public class TriangleCalculator implements Calculator{
private final List<Coordinate> coordinateList;

public TriangleCalculator(List<Coordinate> coordinateList) {
this.coordinateList = coordinateList;
}

@Override
public double calculator() {
//꼭지점 A,B,C
Coordinate coordinateA = coordinateList.get(0);
Coordinate coordinateB = coordinateList.get(1);
Coordinate coordinateC = coordinateList.get(2);
//변AB,변BC,변CA 의 길이
double lineLengthAB = calculateLineLength(coordinateA, coordinateB);
double lineLengthBC = calculateLineLength(coordinateB, coordinateC);
double lineLengthCA = calculateLineLength(coordinateC, coordinateA);
//헤론의 법칙 :(변AB+변BC+변CA)/2 = s
double s = (lineLengthAB + lineLengthBC + lineLengthCA)/2;
// 루트(s*(s-AB)*(s-BC)*(s-CA))
return Math.sqrt(s * (s - lineLengthAB) * (s - lineLengthBC) * (s - lineLengthCA));
}

@Override
public int getCoordinateCount() {
return coordinateList.size();
}

private double calculateLineLength(Coordinate coordinateA, Coordinate coordinateB){
int x = Math.abs(coordinateA.getX() - coordinateB.getX());
int y = Math.abs(coordinateA.getY() - coordinateB.getY());
double somPow = Math.pow(x, 2) + Math.pow(y, 2);
return Math.sqrt(somPow);
}
}
45 changes: 45 additions & 0 deletions src/main/java/domain/Coordinate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package domain;

import java.io.IOException;

public class Coordinate {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coordinate 라는 변수명은 조금 어색한 것 같아요! 아마도 점의 위치를 표현하는 객체같아서, Point 내지 Dot 이라는 변수명은 어떨까요?

int x;
int y;

public Coordinate(String coordinateInput) throws IOException {
//인풋값에서 괄호 없애기
coordinateInput = removeFirstAndLastChar(coordinateInput);
//,기준으로 잘라서 x,y좌표
String[] splitCoordinate = coordinateInput.split(",");
//좌표 크기 검증
validateCoordinateSize(splitCoordinate);

this.x = Integer.parseInt(splitCoordinate[0]);
this.y = Integer.parseInt(splitCoordinate[1]);
}

/**
* (10,13)에서 () 없애주는 메서드
* @param coordinateInput : (10,13)
* @return : 10,13
*/
private String removeFirstAndLastChar(String coordinateInput){
return coordinateInput.substring(1,coordinateInput.length()-1);
}

private void validateCoordinateSize(String[] splitCoordinate) throws IOException {
for (String coordinate:splitCoordinate) {
if (Integer.parseInt(coordinate)<0 || Integer.parseInt(coordinate)>24){
throw new IOException("좌표값은 0부터 24까지만 입력해야합니다.");
}
}
}

public int getX() {
return x;
}

public int getY() {
return y;
}
}
41 changes: 41 additions & 0 deletions src/main/java/view/InputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package view;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputView {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;

public String[] creatCoordinate() throws IOException {
System.out.println("(x,y)-(x,y)또는 (x,y)-(x,y)-(x,y)또는 (x,y)-(x,y)-(x,y)-(x,y)형식으로");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

출력부를 나누는 것은 어떨까요?(완전히 분리)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아직 inputView 와 outputView 나누는 것에 조금 헷갈려요. 다른사람의 코드를 보고 조금 더 참고해서 다음 도전때는 좀 더 분리해보도록 할게요

System.out.println("좌표를 입력하세요");
input = br.readLine();
validateInput(input);
return input.split("-");
}

private void validateInput(String input) throws IOException{
String coordinateInput = "\\(\\d+,\\d+\\)-\\(\\d+,\\d+\\)";
String triangleInput = "\\(\\d+,\\d+\\)-\\(\\d+,\\d+\\)-\\(\\d+,\\d+\\)";
String quadrangleInput = "\\(\\d+,\\d+\\)-\\(\\d+,\\d+\\)-\\(\\d+,\\d+\\)-\\(\\d+,\\d+\\)";

if(!(input.matches(coordinateInput)||input.matches(triangleInput)||input.matches(quadrangleInput))){
throw new IOException("입력값을 형식에 맞게 입력해주세요.");
}
}













}
19 changes: 19 additions & 0 deletions src/main/java/view/OutputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package view;

import calculator.Calculator;
import domain.Coordinate;

import java.util.List;

public class OutputView {


public String resultOutput(Calculator calculator, double result){
if(calculator.getCoordinateCount()==2) return String.format("두 좌표의 길이는 %.6f",result);
if(calculator.getCoordinateCount()==3) return String.format("삼각형의 넓이는 %.2f",result);
if(calculator.getCoordinateCount()==4) return String.format("사각형의 넓이는 %.1f",result);

return "";
};
}

33 changes: 33 additions & 0 deletions src/test/java/domain/CoordinateTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package domain;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.junit.jupiter.api.Assertions.*;

class CoordinateTest {

@DisplayName("Coordinate가 잘 생성되는지 테스트")
@Test
void createCoordinate() throws IOException {
//given
//when
Coordinate coordinate = new Coordinate("(14,24)");
//then
Assertions.assertThat(coordinate.x).isEqualTo(14);
Assertions.assertThat(coordinate.y).isEqualTo(24);
}

@DisplayName("좌표값은 최대 24까지만 입력해야 한다.")
@Test
void validateCoordinateSize() throws IOException {
//given
//when
//then
Assertions.assertThatThrownBy(()-> new Coordinate("(50,24)")).hasMessage("좌표값은 0부터 24까지만 입력해야합니다.");
}

}