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
43 changes: 43 additions & 0 deletions src/main/java/StringAddCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringAddCalculator {
public static boolean isValidationCheckNullOrEmpty(String str) {
return str == null || str.isEmpty();
}

public static boolean isValidationCheckSize1(String str) {
return str.length() == 1;
}

private static int standardStringAddCalculator(String text) {
String[] numbers = text.split(",|:");
if(Arrays.toString(numbers).contains("-")){
throw new RuntimeException();
}
return Arrays.stream(numbers).mapToInt(Integer::parseInt).sum();
}

private static Integer customDelimiterAddCalculator(String str) {
Matcher m = Pattern.compile("//(.)\n(.*)").matcher(str);
if (m.find()) {
String customDelimiter = m.group(1);
String[] numbers = m.group(2).split(customDelimiter);

return Arrays.stream(numbers).mapToInt(Integer::parseInt).sum();
}
return null;
}

public static int splitAndSum(String str) {
if(isValidationCheckNullOrEmpty(str)) return 0;
if(isValidationCheckSize1(str)) return Integer.parseInt(str);

try{ return standardStringAddCalculator(str);}
catch (NumberFormatException numberFormatException){
return customDelimiterAddCalculator(str);
}

}
}
45 changes: 45 additions & 0 deletions src/test/java/StringAddCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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 {
@Test
public void splitAndSum_null_또는_빈문자() {
int result = StringAddCalculator.splitAndSum(null);
assertThat(result).isEqualTo(0);

result = StringAddCalculator.splitAndSum("");
assertThat(result).isEqualTo(0);
}

@Test
public void splitAndSum_숫자하나() throws Exception {
int result = StringAddCalculator.splitAndSum("1");
assertThat(result).isEqualTo(1);
}

@Test
public void splitAndSum_쉼표구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("1,2");
assertThat(result).isEqualTo(3);
}

@Test
public void splitAndSum_쉼표_또는_콜론_구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("1,2:3");
assertThat(result).isEqualTo(6);
}

@Test
public void splitAndSum_custom_구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("//;\n1;2;3");
assertThat(result).isEqualTo(6);
}

@Test
public void splitAndSum_negative() throws Exception {
assertThatThrownBy(() -> StringAddCalculator.splitAndSum("-1,2,3"))
.isInstanceOf(RuntimeException.class);
}
}