Jelajahi Sumber

add negative number handling

Konrad Barszczyk 3 tahun lalu
induk
melakukan
4ce0b5748c

+ 33 - 0
.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/

+ 7 - 0
src/main/java/pl/konrad/NegativeNumberException.java

@@ -0,0 +1,7 @@
+package pl.konrad;
+
+public class NegativeNumberException extends RuntimeException{
+    public NegativeNumberException(String message) {
+        super(message);
+    }
+}

+ 3 - 4
src/main/java/pl/konrad/StringCalculator.java

@@ -9,10 +9,6 @@ public class StringCalculator {
             return 0;
         }
 
-        if (s.contains("-")) {
-            throw new RuntimeException("negatives not allowed");
-        }
-
         if (s.charAt(0) == '/') {
             char delimiter = s.charAt(2);
             String stringToCalc = s.substring(4);
@@ -21,6 +17,9 @@ public class StringCalculator {
             int sum = 0;
 
             for (char value : c) {
+                if (value == '-') {
+                    throw new NegativeNumberException("negatives not allowed");
+                }
                 int a = Integer.parseInt(String.valueOf(value));
                 sum = sum + a;
             }

+ 6 - 2
src/test/java/StringCalculatorTest.java

@@ -1,5 +1,6 @@
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
+import pl.konrad.NegativeNumberException;
 import pl.konrad.StringCalculator;
 
 public class StringCalculatorTest {
@@ -35,8 +36,11 @@ public class StringCalculatorTest {
 
 
     @Test
-    public void testStringCalcForNegativeNumbers(){
-        Assertions.assertThrows(RuntimeException.class,"")
+    public void testStringCalcForNegativeNumbers() {
+        Exception exception = Assertions.assertThrows(NegativeNumberException.class,()-> test(3, "//;\n1;-2"));
+        Assertions.assertEquals("negatives not allowed",exception.getMessage());
+        Exception exception2 = Assertions.assertThrows(NegativeNumberException.class,()->   test(11, "//a\n3a-3a-5"));
+        Assertions.assertEquals("negatives not allowed",exception2.getMessage());
     }