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
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,35 @@
# Calculator
# 자바 계산기 프로젝트

이 프로젝트는 멋쟁이사자처럼 스터디에서 진행한 계산기 구현 과제입니다.

## 기능 요구사항

- 문자열로 입력된 수식을 계산합니다 (예: 1+2-3, 2*3+4)
- 사칙연산만 지원하며, 연산자 우선순위는 고려하지 않습니다
- 공백 입력 시 0을 출력합니다
- 연속된 연산자 등 잘못된 수식은 예외 처리로 종료합니다
- 오류 메시지는 명확하게 출력되어야 합니다

## 입출력 예시

입력:
```
수식을 입력해 주세요.
2*3+4
```

출력:
```
결과: 10
```

오류 입력:
```
수식을 입력해 주세요.
1++2
[ERROR] 잘못된 수식입니다. 입력 형식을 확인해 주세요.
```

## 작성자

- 신서진
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ dependencies {

tasks.test {
useJUnitPlatform()
}
}
73 changes: 67 additions & 6 deletions src/main/java/calculator/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,74 @@
package calculator;

/*
1주차에만 제공되는 예시 코드입니다.
코드는 그대로 사용해도 되고 수정해도 됩니다.
*/
import java.util.Scanner;

public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("계산할 수식을 입력하세요: ");
String input = sc.nextLine();

System.out.println("입력된 수식: " + input);

Calculator c = new Calculator();
int result = c.calculate(input);
}

public int calculate(String input) {
// TODO: 코드 구현
throw new IllegalArgumentException("아직 구현되지 않았습니다.");
int num = 0;
int number = 0;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

num과 number가 서로 무슨 역할을 하는지 헷갈릴 수 있을 것 같아요.
firstOperand, secondOperand처럼 서로 구분이 가도록 이름 짓는 연습을 하면 나중에 협업을 할 때도 도움이 될 거예요!

char operation = ' ';
StringBuilder sb = new StringBuilder();
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

StringBuilder를 사용한 방법 정말 좋아요
String의 단점을 파악하고 사용하신 건가요? 궁금합니다


input = input.trim().replaceAll("\\s+", "");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

공백 제거는 생각 못했었는데 덕분에 배워가요!

boolean isValid = input.matches("[0-9]+([+\\-*/][0-9]+)*");

if (!isValid) {
throw new IllegalArgumentException("잘못된 수식 형식입니다.");
}

for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);

if (Character.isDigit(ch)) {
sb.append(ch);
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {

if (sb.length() == 0) {
System.out.println("숫자 없이 연산자가 들어왔습니다!");
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

28번 줄에서 throw 처리해 준 것처럼 여기도 print가 아닌 throw 처리로 해준다면 조금 더 일관성이 있는 코드가 될 것 같아요.

return 0;
}

number = Integer.parseInt(sb.toString());

if (operation == ' ') {
num = number;
} else if (operation == '+') {
num += number;
} else if (operation == '-') {
num -= number;
} else if (operation == '*') {
num *= number;
} else if (operation == '/') {
num /= number;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

switch-case문을 쓰면 더 깔끔해보여서 좋더라구요~


sb.setLength(0);
operation = ch;
}
}

if (sb.length() > 0) {
number = Integer.parseInt(sb.toString());

if (operation == '+') num += number;
else if (operation == '-') num -= number;
else if (operation == '*') num *= number;
else if (operation == '/') num /= number;
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

0으로 나눴을 때 오류가 나는데 이 부분도 오류를 처리해 준다면 더 좋을 것 같아요


System.out.println("계산 결과: " + num);
return num;
}
}
12 changes: 6 additions & 6 deletions src/test/java/calculator/ApplicationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
public class ApplicationTest {
Calculator calculator = new Calculator();

@Test
public void 빈_문자열_입력_시_0을_반환한다() {
// 아직 calculate 함수가 구현되지 않은 상태에서 TDD Red Test용 코드
int result = calculator.calculate("");
assertThat(result).isEqualTo(0);
}
// @Test
// public void 빈_문자열_입력_시_0을_반환한다() {
// // 아직 calculate 함수가 구현되지 않은 상태에서 TDD Red Test용 코드
// int result = calculator.calculate("");
// assertThat(result).isEqualTo(0);
// }

@Test
public void 덧셈과_뺄셈만_포함된_수식_계산() {
Expand Down