Requirement – single operations

So, the plan is to support add, subtract, multiply and divide operations. As explained in the kata presentation, in RPN the operator is located at the end of the expression.

That means a - b is represented as a b -, and the same applies to the other operators: addition +,  multiplication *,  and division /.

Let's add one of each of the supported operations to our tests:

@Test
public void addOperationReturnsCorrectValue() {
assertThat(reversePolishNotation.compute("1 2 +")).isEqualTo(3);
}

@Test
public void subtractOperationReturnsCorrectValue() {
assertThat(reversePolishNotation.compute("2 1 -")).isEqualTo(1);
}

@Test
public void multiplyOperationReturnsCorrectValue() {
assertThat(reversePolishNotation.compute("2 1 *")).isEqualTo(2);
}

@Test
public void divideOperationReturnsCorrectValue() {
assertThat(reversePolishNotation.compute("2 2 /")).isEqualTo(1);
}

This also includes the necessary changes to make them pass successfully. The behavior is basically placing the operator between the expressions and performing the operation in case an expression is given as input. If there is only one element in the expression, then the former rules apply:

int compute(String expression) {
String[] elems = expression.trim().split(" ");
if (elems.length != 1 && elems.length != 3)
throw new NotReversePolishNotationError();
if (elems.length == 1) {
return parseInt(elems[0]);
} else {
if ("+".equals(elems[2]))
return parseInt(elems[0]) + parseInt(elems[1]);
else if ("-".equals(elems[2]))
return parseInt(elems[0]) - parseInt(elems[1]);
else if ("*".equals(elems[2]))
return parseInt(elems[0]) * parseInt(elems[1]);
else if ("/".equals(elems[2]))
return parseInt(elems[0]) / parseInt(elems[1]);
else
throw new NotReversePolishNotationError();
}
}

parseInt is a private method that parses the input and either returns the integer value or throws an exception:

private int parseInt(String number) {
try {
return Integer.parseInt(number);
} catch (NumberFormatException e) {
throw new NotReversePolishNotationError();
}
}

The next requirement is where the magic happens. We are going to support more than one operation within the expression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.51.36