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
77 changes: 77 additions & 0 deletions Step2/kimnahyun/src/main/Main.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
41 changes: 41 additions & 0 deletions Step2/kimnahyun/src/test/StringCalculator_Test.java
Original file line number Diff line number Diff line change
@@ -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");
}
}