Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static org.junit.Assert.assertEquals;
- import org.junit.Before;
- import org.junit.Rule;
- import org.junit.Test;
- import org.junit.rules.ExpectedException;
- import java.lang.Object;
- import java.util.Stack;
- public class TestJunitRevPolishCalc {
- String[] splitArray;
- int first, number;
- LeafNode nodeLeaf, nodeLeaf0, nodeLeaf1;
- Stack<LeafNode> myStack;
- OperatorNode opNode;
- SumVisitor sumVisitor;
- // for tests
- boolean bo;
- String str;
- @Before
- public void setUp() {
- str = new String("3 4 +");
- splitArray = new String[3];
- myStack = new Stack<LeafNode>();
- }
- public boolean isNumeric(String str) {
- try {
- double d = Double.parseDouble(str);
- } catch (NumberFormatException nfe) {
- return false;
- }
- return true;
- }
- public boolean isSymbol(String str) {
- String[] symbolArray = {"+", "-", "/", "*"};
- for (int j = 0; j < symbolArray.length; j++) {
- if (str == symbolArray[j]) {
- return true;
- }
- }
- return false;
- }
- @Test
- public void testArray() {
- splitArray = str.split(" ");
- first = Integer.parseInt(splitArray[0]);
- assertEquals(first, 3, 0f);
- }
- @Test
- public void testIsNumeric() {
- splitArray = str.split(" ");
- assertEquals(isNumeric(splitArray[0]), true);
- }
- @Test
- public void testIsSymbol() {
- splitArray = str.split(" ");
- for (int i = 0; i < splitArray.length; i++) {
- bo = isSymbol(splitArray[i]);
- }
- assertEquals(bo, true);
- }
- @Test
- public void testRevPolishCalc0() throws BadTypeException, EmptyStackException {
- int i = 0;
- splitArray = str.split(" ");
- while (i < splitArray.length) {
- if (isNumeric(splitArray[i]) == true) {
- number = Integer.parseInt(splitArray[i]);
- nodeLeaf = new LeafNode(number);
- myStack.push(nodeLeaf);
- }
- if (isSymbol(splitArray[i]) == true) {
- nodeLeaf0 = myStack.pop();
- nodeLeaf1 = myStack.pop();
- switch (splitArray[i]) {
- case "+":
- Operator pl = Plus.getInstance();
- opNode = new OperatorNode(pl, nodeLeaf0, nodeLeaf1);
- break;
- case "-":
- Operator mi = Minus.getInstance();
- opNode = new OperatorNode(mi, nodeLeaf0, nodeLeaf1);
- break;
- case "*":
- Operator ti = Times.getInstance();
- opNode = new OperatorNode(ti, nodeLeaf0, nodeLeaf1);
- break;
- default:
- break;
- }
- //in the class return element on top of the stack
- sumVisitor = new SumVisitor();
- sumVisitor.visit(opNode);
- }
- }
- nodeLeaf = new LeafNode(sumVisitor.getAnswer());
- myStack.push(nodeLeaf);
- assertEquals(myStack.pop().getValue(),7,0f);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement