Skip to content

Commit

Permalink
To be refactored: String Calculator
Browse files Browse the repository at this point in the history
  • Loading branch information
Grzegorz Dziemidowicz committed Nov 24, 2011
1 parent 1a314b9 commit 9e9ef1c
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
30 changes: 30 additions & 0 deletions java/string_calculator/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>string_calculator</groupId>
<artifactId>string_calculator</artifactId>
<version>1.0</version>

<dependencies>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.1</version>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.0-rc1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
</dependencies>

</project>
20 changes: 20 additions & 0 deletions java/string_calculator/src/main/java/StringCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class StringCalculator {
public int add(String s) {
if (s.isEmpty()) {
return 0;
}
if (s.startsWith("//")) {
int returnValue = 0;
for (String n : s.substring(4).split("[\n"+ s.charAt(2) +"]")) {
returnValue += Integer.parseInt(n);
}
return returnValue;
} else {
int r = 0; // result
for (String n : s.split("[\n,]")) {
r += Integer.parseInt(n);
}
return r;
}
}
}
16 changes: 16 additions & 0 deletions java/string_calculator/src/test/java/StringCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class StringCalculatorTest {

@Test
public void testCalculator() throws Exception {
StringCalculator s = new StringCalculator();
assertEquals(0, s.add("")); //should treat empty string as zero
assertEquals(17, s.add("17")); // should add single numbers
assertEquals(2356, s.add("2341,15")); // should add comma separated numbers
assertEquals(35, s.add("34\n1")); // should treat new line as separator
assertEquals(7, s.add("//;\n5;2")); // should support custom separators
}
}

0 comments on commit 9e9ef1c

Please sign in to comment.