diff --git a/src/main/java/htw/berlin/prog2/ha1/Calculator.java b/src/main/java/htw/berlin/prog2/ha1/Calculator.java index 84c04f2..04e9af4 100644 --- a/src/main/java/htw/berlin/prog2/ha1/Calculator.java +++ b/src/main/java/htw/berlin/prog2/ha1/Calculator.java @@ -33,7 +33,9 @@ public void pressDigitKey(int digit) { if(screen.equals("0") || latestValue == Double.parseDouble(screen)) screen = ""; + if (screen.length() < 9) { screen = screen + digit; + } } /** @@ -74,6 +76,10 @@ public void pressBinaryOperationKey(String operation) { public void pressUnaryOperationKey(String operation) { latestValue = Double.parseDouble(screen); latestOperation = operation; + if (operation.equals("1/x") && Double.parseDouble(screen) == 0) { + screen = "Error"; + return; + } var result = switch(operation) { case "√" -> Math.sqrt(Double.parseDouble(screen)); case "%" -> Double.parseDouble(screen) / 100; diff --git a/src/test/java/htw/berlin/prog2/ha1/CalculatorTest.java b/src/test/java/htw/berlin/prog2/ha1/CalculatorTest.java index ddff0da..1a24238 100644 --- a/src/test/java/htw/berlin/prog2/ha1/CalculatorTest.java +++ b/src/test/java/htw/berlin/prog2/ha1/CalculatorTest.java @@ -1,10 +1,9 @@ package htw.berlin.prog2.ha1; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - @DisplayName("Retro calculator") class CalculatorTest { @@ -88,7 +87,48 @@ void testMultipleDecimalDots() { assertEquals(expected, actual); } + @Test + @DisplayName("should display entered number after pressing digit keys") + void testEnteredNumber() { + Calculator calc = new Calculator(); + + calc.pressDigitKey(1); + calc.pressDigitKey(2); + calc.pressDigitKey(3); + + String expected = "123"; + String actual = calc.readScreen(); + + assertEquals(expected, actual); + } + + @Test + @DisplayName("should display error when calculating inverse of zero") + void testInverseOfZero() { + Calculator calc = new Calculator(); - //TODO hier weitere Tests erstellen -} + calc.pressDigitKey(0); + calc.pressUnaryOperationKey("1/x"); + + String expected = "Error"; + String actual = calc.readScreen(); + + assertEquals(expected, actual); + } + + @Test + @DisplayName("should not allow more than 9 digits on display") + void testMaxDigits() { + Calculator calc = new Calculator(); + + for (int i = 0; i < 11; i++) { + calc.pressDigitKey(1); + } + + String expected = "111111111"; + String actual = calc.readScreen(); + + assertEquals(expected, actual); + } +} \ No newline at end of file