diff --git a/Step2/kimnahyun/src/main/Main.java b/Step2/kimnahyun/src/main/Main.java new file mode 100644 index 0000000..c3eebf5 --- /dev/null +++ b/Step2/kimnahyun/src/main/Main.java @@ -0,0 +1,77 @@ +package main; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Main { + public static void main(String[] args) { + Calculator cal = new Calculator(); + } + + public static class Calculator { + int add(int i, int j){ + return i + j; + } + + int subtract(int i, int j) { + return i - j; + } + + int multiply(int i, int j) { + return i * j; + } + + int divide(int i, int j) { + return i / j; + } + + } + + public static class StringCalculator { + + public int add(String text) { + if (toBlank(text)) { + return 0; + } + + return sum(toInts(split(text))); + } + + private boolean toBlank(String text) { + return text == null || text.isEmpty(); + } + + private String[] split(String text) { + Matcher m = Pattern.compile("//(.)\n(.*)").matcher(text); + if (m.find()) { + String customDelimeter = m.group(1); + return m.group(2).split(customDelimeter); + } + return text.split(",|:"); + } + + private int[] toInts(String[] values) { + int[] numbers = new int[values.length]; + for (int i = 0; i < values.length; i++) { + numbers[i] = toPositive(values[i]); + } + return numbers; + } + + private int sum(int[] numbers) { + int sum = 0; + for (int num : numbers) { + sum += num; + } + return sum; + } + + private int toPositive(String value) { + int number = Integer.parseInt(value); + if (number < 0) { + throw new RuntimeException(); + } + return number; + } + } +} \ No newline at end of file diff --git a/Step2/kimnahyun/src/test/StringCalculator_Test.java b/Step2/kimnahyun/src/test/StringCalculator_Test.java new file mode 100644 index 0000000..b421b8d --- /dev/null +++ b/Step2/kimnahyun/src/test/StringCalculator_Test.java @@ -0,0 +1,41 @@ +package test; + +import main.Main; +import org.junit.Before; +import org.junit.Test; +/*import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach;*/ + +import static org.junit.jupiter.api.Assertions.*; + +public class StringCalculator_Test { + private Main.StringCalculator cal; + + @Before + public void setup() { + cal = new Main.StringCalculator(); + System.out.println("Before"); + } + @Test + public void add_empty() { + assertEquals(0,cal.add(null)); + assertEquals(0,cal.add("")); + } + @Test + public void add_string() { + assertEquals(3, cal.add("3")); + } + @Test + public void add_seperate() { + assertEquals(8,cal.add("6,2")); + assertEquals(9,cal.add("3,2:4")); + } + @Test + public void add_regx() { + assertEquals(8, cal.add("//;\n3;4;1")); + } + @Test(expected = RuntimeException.class) + public void add_minus() { + cal.add("-1,2,3"); + } +} \ No newline at end of file