Skip to content
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단계 - 문자열 계산기 #5657

Open
wants to merge 27 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
afb3952
1단계 - 학습테스트 실습 (#5569)
kdfasdf Sep 24, 2024
7f59c4d
feat: implement requirement 1
kdfasdf Sep 26, 2024
a7c96bb
feat: implement requirement 2
kdfasdf Sep 27, 2024
e808659
feat: implement requirement 3
kdfasdf Sep 27, 2024
2724f87
implement requirement 4
kdfasdf Sep 27, 2024
7255cec
feat: implement requirement 5
kdfasdf Sep 27, 2024
d751a21
chore : rename file
kdfasdf Sep 27, 2024
81050ba
feat : implement requirement 6
kdfasdf Sep 27, 2024
a6163b7
chore : 미사용 파일 삭제 및 주석 추가
kdfasdf Sep 27, 2024
823b6cb
chore : 구현 내용 초기화
kdfasdf Sep 27, 2024
bedc9d1
feat : 요구사항1 구현
kdfasdf Sep 27, 2024
00b6c48
feat : 요구사항2 구현
kdfasdf Sep 27, 2024
4f9474d
feat : 요구사항 3 구현
kdfasdf Sep 27, 2024
7da8790
feat : 요구사항 4 구현
kdfasdf Sep 27, 2024
e557d7a
feat : 요구사항 5 구현
kdfasdf Sep 27, 2024
7415048
feat : 요구사항 6 구현
kdfasdf Sep 27, 2024
3fad8a6
chore : 상수추출 및 불필요한 메서드(validnegative) 제거
kdfasdf Sep 27, 2024
c8ea667
refactor : 숫자 합을 구하는 공통 로직, calculateSum 메서드로 추출
kdfasdf Sep 27, 2024
15b2371
chore : 불필요한 지역변수 제거
kdfasdf Sep 27, 2024
2249f09
refactor : if문 validNegativeNumberString메서드로 분리
kdfasdf Sep 27, 2024
188ea61
refactor : 정수 형변환 toInt()메서드로 책임 분리
kdfasdf Sep 27, 2024
8604a7e
chore : 코드 자동 정렬
kdfasdf Sep 27, 2024
3f0e234
refactor : 요구사항 1, 2 재구현 및 private() 생성자
kdfasdf Sep 28, 2024
639fcfc
refactor : 요구사항 3 재구현
kdfasdf Sep 28, 2024
4a4aa08
refactor : 요구사항 4 재구현
kdfasdf Sep 28, 2024
13c2117
refactor : 피드백 반영 및 요구사항 5 재구현
kdfasdf Sep 28, 2024
f9458c1
refactor : 요구사항 6 재구현 및 피드백 반영
kdfasdf Sep 28, 2024
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
Empty file removed src/main/java/.gitkeep
Empty file.
65 changes: 65 additions & 0 deletions src/main/java/StringAddCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringAddCalculator {

public static final String COMMA = ",";
public static final String DELIMETER = ",|:";
public static final String CUSTOMDELIMETER = "//(.)\n(.*)";
public static final int DEFAULT_VALUE_OF_NULL_AND_EMPTYSTRING = 0;
public static final Pattern pattern = Pattern.compile(CUSTOMDELIMETER);

private StringAddCalculator() {
throw new RuntimeException();
}

public static int splitAndSum(String input) {
if (input == null || input.isEmpty()) {
return DEFAULT_VALUE_OF_NULL_AND_EMPTYSTRING;
}
Matcher m = pattern.matcher(input);
if (m.find()) {
String customDelimiter = m.group(1);
String[] tokens = m.group(2).split(customDelimiter);
return calculateSum(toInt(tokens));
}
String[] splited = input.split(DELIMETER);
return calculateSum(toInt(splited));
}

private static int calculateSum(int[] splited) {
int summation = 0;
for (int num : splited) {
isNegative(num);
summation += num;
}
return summation;
}

private static void isNegative(int num) {
if (num < 0) {
throw new RuntimeException();
}
}

private static int[] toInt(String[] splited) {
int[] numbers = new int[splited.length];
for (int i = 0; i < splited.length; i++) {
numbers[i] = Integer.parseInt(checkDigit(splited[i]));
}
return numbers;
}

private static String checkDigit(String input) {
for (char c : input.toCharArray()) {
valudateDigit(c);
}
return input;
}

private static void valudateDigit(char c) {
if (!Character.isDigit(c)) {
throw new RuntimeException();
}
}
}
Empty file removed src/test/java/.gitkeep
Empty file.
45 changes: 45 additions & 0 deletions src/test/java/SetCollectionTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.HashSet;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

class SetCollectionTest {
private Set<Integer> numbers;

@BeforeEach
void setUp() {
numbers = new HashSet<>();
numbers.add(1);
numbers.add(1);
numbers.add(2);
numbers.add(3);
}

@Test
@DisplayName("size()로 Set의 크기 확인")
void sizeTest() {
assertThat(numbers).hasSize(3);
}


@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
@DisplayName("contains()로 set에 있는 값 확인")
void containsTest(int number) {
assertThat(numbers.contains(number));
}

@ParameterizedTest
@CsvSource(value = {"1:true", "2:true", "3:true", "4:false", "5:false"}, delimiter = ':')
@DisplayName("contains()로 다양한 값 확인")
void containsTest2(int value, boolean expected) {
assertThat(numbers.contains(value)).isEqualTo(expected);
}
}
64 changes: 64 additions & 0 deletions src/test/java/StringAddCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class StringAddCalculatorTest {
@ParameterizedTest
@EmptySource
@NullSource
@DisplayName("빈 문자열 또는 null이면 0을 반환")
void whenGivenNullOrEmpty(String input) {
int result = StringAddCalculator.splitAndSum(input);

assertThat(result).isEqualTo(0);
}

@Test
@DisplayName("숫자 하나를 입력할 경우 해당 숫자를 반환한다")
void inputOneNumberStringReturnToInteger() {
int result = StringAddCalculator.splitAndSum("1");

assertThat(result).isEqualTo(1);
}

@ParameterizedTest
@ValueSource(strings = {"1,2"})
@DisplayName("숫자 두개를 컴마(,) 구분자로 입력할 경우 두 숫자의 합을 반환")
void splitAndSumWithComma(String input) {
int result = StringAddCalculator.splitAndSum(input);

assertThat(result).isEqualTo(3);
}

@ParameterizedTest
@ValueSource(strings = {"1,2:3"})
@DisplayName("구분자를 컴마 이외에 콜론을 사용할 수 있다")
void splitAndSumWithCommaOrColon(String input) {
int result = StringAddCalculator.splitAndSum(input);

assertThat(result).isEqualTo(6);
}

@ParameterizedTest
@ValueSource(strings = {"//;\n1;2;3"})
@DisplayName("\"//\"와 \"\\n\" 사이의 문자를 커스텀 구분자 사용")
void customDelimeter(String input) {
int result = StringAddCalculator.splitAndSum(input);

assertThat(result).isEqualTo(6);
}

@ParameterizedTest
@ValueSource(strings = {"-1,2,3"})
@DisplayName("음수를 전달할 경우 RuntimeException 발생")
void negativeThrowRuntimeException(String input) {
assertThatThrownBy(() -> StringAddCalculator.splitAndSum(input))
.isInstanceOf(RuntimeException.class);
}
}
60 changes: 60 additions & 0 deletions src/test/java/StringClassTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class StringClassTest {
@Test
@DisplayName("\"1,2\"를 ,로 split 했을 때 분리되는지")
void splitTest1() {
//given
String str = "1,2";

//when
String[] result = str.split(",");

//Then
assertThat(result).containsExactly("1", "2");
}

@Test
@DisplayName("\"1\"을 ,로 split 했을 때 {\"1\"}로 반환되는지")
void splitTest2() {
String[] result = "1".split(",");

assertThat(result).contains("1");
}

@Test
@DisplayName("substring()을 통해 ()제거")
void subStringTest() {
String str = "(1,2)";

String result = str.substring(1, str.length() - 1);

assertThat(result).isEqualTo("1,2");
}

@Test
@DisplayName("charAt()을 통해 문자열 범위 안 문자 가져오기")
void charAt_범위_안() {
final String str = "abc";

char result = str.charAt(1);

assertThat(result).isEqualTo('b');
}

@Test
@DisplayName("charAt()을 통해 문자열 범위 밖 문자 가져오기")
void charAt_범위_밖() {
final String str = "abc";

assertThatThrownBy(() -> {
str.charAt(str.length());
}).isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageContaining("String index out of range:");
}

}