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
23 changes: 18 additions & 5 deletions src/main/java/tdd/setup/Calculator.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
// behaviour inspired by https://www.online-calculator.com/
public class Calculator {

private String screen = "0";
private String screen = "";

private double latestValue;

private double firstValue;

private double secondValue;
private double thirdValue;

private String latestOperation = "";

public String readScreen() {
Expand All @@ -17,11 +22,19 @@ public void pressDigitKey(int digit) {

if(latestOperation.isEmpty()) {
screen = screen + digit;
} else {
firstValue = Double.parseDouble(screen);

}
if(!screen.contains(".")) {
latestValue = Double.parseDouble(screen);
screen = Integer.toString(digit);

}
else {
screen = screen + digit;
latestValue = Double.parseDouble(screen);
}
}
}

public void pressClearKey() {
screen = "0";
Expand All @@ -42,8 +55,8 @@ public void pressNegative() {
}

public void pressEquals() {
var result = switch(latestOperation) {
case "+" -> latestValue + Double.parseDouble(screen);
var result = switch(latestOperation){
case "+" -> firstValue + Double.parseDouble(screen);
case "-" -> latestValue - Double.parseDouble(screen);
case "x" -> latestValue * Double.parseDouble(screen);
case "/" -> latestValue / Double.parseDouble(screen);
Expand Down
36 changes: 36 additions & 0 deletions src/test/java/tdd/setup/CalculatorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,39 @@ void calculatorCanDoTwoPlusTwo() {
assertEquals("4", calc.readScreen());
}
}
class CalculatorTest2 {
@Test
@DisplayName("should display result after subtracting two positive numbers")
void calculatorCanDoThreeMinusTwo() {
Calculator calc = new Calculator();
calc.pressDigitKey(3);
calc.pressOperationKey("-");
calc.pressDigitKey(2);
calc.pressEquals();
assertEquals("1", calc.readScreen());
}
}
class CalculatorTest3 {
@Test
@DisplayName("should display result after pressDigitKey")
void calculatorCanMulti() {
Calculator calc = new Calculator();
calc.pressDigitKey(2);
assertEquals("2", calc.readScreen());
}
}
class CalculatorTest4 {
@Test
@DisplayName("should display result after adding two positive point numbers")
void calculatorCanDoTwoPlusTwo() {
Calculator calc = new Calculator();
calc.pressDigitKey(2);
calc.pressOperationKey("+");
calc.pressDigitKey(3);
calc.pressDotKey();
calc.pressDigitKey(4);
calc.pressEquals();
assertEquals("5.4", calc.readScreen());
}
}