-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[자동차 경주 - 단위테스트] 2단계 - 문자열 덧셈 계산기 #5914
Merged
+113
−32
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7ee25d0
doc: 불필요한 전 단계 요구사항 삭제
gukin-han 2409ca7
test: TestCase 소스 코드
gukin-han 3454c49
test: 테스트 코드 내 displayName 추가
gukin-han b801eb0
feat: 문자열 덧셈 계산기능
gukin-han 501aec9
refactor: private 메서드 순서를 public 내 순서에 맞게 조정
gukin-han 7941374
refactor: 스트링 배열을 불변 컬렉션 리스트 타입으로 반환하도록 수정
gukin-han File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package calculator; | ||
|
||
import java.util.List; | ||
import java.util.regex.Matcher; | ||
import java.util.regex.Pattern; | ||
|
||
public class StringAddCalculator { | ||
|
||
private static final Pattern DEFAULT_DELIMITERS_PATTERN = Pattern.compile("[,:]"); | ||
private static final Pattern CUSTOM_DELIMITER_PARSE_PATTERN = Pattern.compile("//(.)\n(.*)"); | ||
public static final String VALID_INTEGER_PATTERN = "-?\\d+"; | ||
|
||
public static int splitAndSum(String text) { | ||
|
||
if (text == null || text.isEmpty()) { | ||
return 0; | ||
} | ||
|
||
List<String> tokens = splitIntoTokens(text); | ||
return sumPositiveNumbersOrThrow(tokens); | ||
} | ||
|
||
private static List<String> splitIntoTokens(String text) { | ||
Matcher matcher = CUSTOM_DELIMITER_PARSE_PATTERN.matcher(text); | ||
|
||
if (matcher.find()) { | ||
String customDelimiter = Pattern.quote(matcher.group(1)); | ||
return List.of(matcher.group(2).split(customDelimiter)); | ||
} | ||
|
||
return List.of(DEFAULT_DELIMITERS_PATTERN.split(text)); | ||
} | ||
|
||
private static int sumPositiveNumbersOrThrow(List<String> tokens) { | ||
int sum = 0; | ||
for (String token : tokens) { | ||
if (!isValidInteger(token)) { | ||
throw new RuntimeException("Invalid input: " + token); | ||
} | ||
|
||
int num = Integer.parseInt(token); | ||
if (num < 0) { | ||
throw new RuntimeException("Negative numbers not allowed: " + token); | ||
} | ||
|
||
sum += num; | ||
} | ||
return sum; | ||
} | ||
|
||
private static boolean isValidInteger(String input) { | ||
if (input == null || input.isEmpty()) { | ||
return false; | ||
} | ||
return input.matches(VALID_INTEGER_PATTERN); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package calculator; | ||
|
||
import org.junit.jupiter.api.DisplayName; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat; | ||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; | ||
|
||
public class StringAddCalculatorTest { | ||
|
||
@DisplayName("빈 문자열 또는 null 값을 입력할 경우 0을 반환해야 한다.(예 : “” => 0, null => 0)") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. displayname 좋습니다. 👍 |
||
@Test | ||
public void splitAndSum_null_또는_빈문자() { | ||
int result = StringAddCalculator.splitAndSum(null); | ||
assertThat(result).isEqualTo(0); | ||
|
||
result = StringAddCalculator.splitAndSum(""); | ||
assertThat(result).isEqualTo(0); | ||
} | ||
|
||
@DisplayName("숫자 하나를 문자열로 입력할 경우 해당 숫자를 반환한다.(예 : “1”)") | ||
@Test | ||
public void splitAndSum_숫자하나() throws Exception { | ||
int result = StringAddCalculator.splitAndSum("1"); | ||
assertThat(result).isEqualTo(1); | ||
} | ||
|
||
@DisplayName("숫자 두개를 컴마(,) 구분자로 입력할 경우 두 숫자의 합을 반환한다.(예 : “1,2”)") | ||
@Test | ||
public void splitAndSum_쉼표구분자() throws Exception { | ||
int result = StringAddCalculator.splitAndSum("1,2"); | ||
assertThat(result).isEqualTo(3); | ||
} | ||
|
||
@DisplayName("구분자를 컴마(,) 이외에 콜론(:)을 사용할 수 있다. (예 : “1,2:3” => 6)") | ||
@Test | ||
public void splitAndSum_쉼표_또는_콜론_구분자() throws Exception { | ||
int result = StringAddCalculator.splitAndSum("1,2:3"); | ||
assertThat(result).isEqualTo(6); | ||
} | ||
|
||
@DisplayName("“//”와 “\\n” 문자 사이에 커스텀 구분자를 지정할 수 있다. (예 : “//;\\n1;2;3” => 6)") | ||
@Test | ||
public void splitAndSum_custom_구분자() throws Exception { | ||
int result = StringAddCalculator.splitAndSum("//;\n1;2;3"); | ||
assertThat(result).isEqualTo(6); | ||
} | ||
|
||
@DisplayName("음수를 전달할 경우 RuntimeException 예외가 발생해야 한다. (예 : “-1,2,3”)") | ||
@Test | ||
public void splitAndSum_negative() throws Exception { | ||
assertThatThrownBy(() -> StringAddCalculator.splitAndSum("-1,2,3")) | ||
.isInstanceOf(RuntimeException.class); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
헛 요구사항은 왜 굳이 삭제하셨나요?? 삭제 안하셔도 됩니다~!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
제가 임의로 작성한 내용이라서 필요하면 나중에 필요하면 리버트하겠습니다 ㅎ