Question: I am working to write code to Evaluate the given postfix expression. I have wrote a code, but one of the junit test doesnt go

I am working to write code to Evaluate the given postfix expression. I have wrote a code, but one of the junit test doesnt go through. How should i write that "expr contains too few operands". In the evalute I use a stack.

TODO: help to correct the "evaluate(String expr) throws ExpressionException ()" method so all the test in the testclass goes through.

Interface stack:

/** * A interface of stack */ public interface Stack { /** * Adds the element to the top of the stack. */ void push (T elem); /** * Removes and returns the top element in stack, * that is the element that was last added. * Throws an EmptyStackException if stack is empty. */ T pop(); /** * Returns the top element in the stack without removing it. * Throws an EmptyStackException if stack is empty. */ T top(); /** * Returns the number of elements in stack. * @return the number of elements. */ int size(); /** * Returns true if the stack is empty. * @return true. */ boolean isEmpty(); }

LinkedList implements stack

import java.util.EmptyStackException; import java.util.NoSuchElementException; /** * A singly linked list. * */ public class LinkedList implements Stack { private ListElement first; // First element in list. private ListElement last; // Last element in list. private int size; // Number of elements in list. /** * A list element. */ private static class ListElement{ public T data; public ListElement next; public ListElement(T data) { this.data = data; this.next = null; } } /** * Creates an empty list. */ public LinkedList() { this.first = null; this.last = null; this.size = 0; } /** * Inserts the given element at the beginning of this list. * * @param element An element to insert into the list. */ public void addFirst(T element) { ListElement firstElement = new ListElement<>(element); if (this.size == 0){ this.first = firstElement; this.last = firstElement; } else{ firstElement.next = this.first; this.first = firstElement; } this.size ++; } /** * Inserts the given element at the end of this list. * * @param element An element to insert into the list. */ public void addLast(T element) { ListElement lastElement = new ListElement<>(element); if(this.size ==0){ this.first = lastElement; } else{ this.last.next = lastElement; } this.last = lastElement; this.size ++; } /** * @return The head of the list. * @throws NoSuchElementException if the list is empty. */ public T getFirst() { if (this.first != null){ return this.first.data; } else{ throw new NoSuchElementException(); } } /** * @return The tail of the list. * @throws NoSuchElementException if the list is empty. */ public T getLast() { if(this.last != null){ return this.last.data; } else{ throw new NoSuchElementException(); } } /** * Returns an element from a specified index. * * @param index A list index. * @return The element at the specified index. * @throws IndexOutOfBoundsException if the index is out of bounds. */ public T get(int index) { if(index < 0|| index >= this.size){ throw new IndexOutOfBoundsException(); } else{ ListElementelement = this.first; for(int i = 0; i < index; i++){ element = element.next; } return element.data; } } /** * Removes the first element from the list. * * @return The removed element. * @throws NoSuchElementException if the list is empty. */ public T removeFirst() { if(this.first != null || this.size != 0){ ListElement list = this.first; this.first = first.next; size --; if(size() == 0){ last = null; } return list.data; } else{ throw new NoSuchElementException(); } } /** * Removes all of the elements from the list. */ public void clear() { this.first = null; this.last = null; this.size =0; } /** * Adds the element to the top of the stock. * @param elem */ @Override public void push(T elem) { ListElement list = new ListElement<>(elem); if( first == null){ first = list; last = first; } else{ list.next = first; first = list; } size ++; } /** * Removes and returns the top element in stack, * that is the element that was last added. * Throws an EmptyStackException if stack is empty. * @return the top element in the stack. */ @Override public T pop(){ if(isEmpty()){ throw new EmptyStackException(); }else{ ListElement list = first; first = first.next; size --; return list.data; } } /** * returns the top element in the stack without removing it. * Throws an EmptyStackException if stack is empty. * @return the top element. */ @Override public T top() { if(isEmpty()){ throw new EmptyStackException(); }else{ return first.data; } } /** * Returns the number of elements in the stock * @return The number of elements in the stock. */ public int size() { return this.size; } /** * Note that by definition, the list is empty if both first and last * are null, regardless of what value the size field holds (it should * be 0, otherwise something is wrong). * * @return true if this list contains no elements. */ public boolean isEmpty() { return first == null && last == null; } /** * Creates a string representation of this list. The string * representation consists of a list of the elements enclosed in * square brackets ("[]"). Adjacent elements are separated by the * characters ", " (comma and space). Elements are converted to * strings by the method toString() inherited from Object. * * Examples: * "[1, 4, 2, 3, 44]" * "[]" * * @return A string representing the list. */ public String toString() { ListElement listOfElements = this.first; String returnString = "["; while(listOfElements != null) { returnString += listOfElements.data; if(listOfElements.next != null){ returnString += ", "; } listOfElements = listOfElements.next; } returnString += "]"; return returnString; } }
postfix class: import java.util.Scanner; import java.util.Stack; /** * The Postfix class implements an evaluator for integer postfix expressions. * * Postfix notation is a simple way to define and write arithmetic expressions * without the need for parentheses or priority rules. For example, the postfix * expression "1 2 - 3 4 + *" corresponds to the ordinary infix expression * "(1 - 2) * (3 + 4)". The expressions may contain decimal 32-bit integer * operands and the four operators +, -, *, and /. Operators and operands must * be separated by whitespace. * */ public class Postfix { public static class ExpressionException extends Exception { public ExpressionException(String message) { super(message); } } 
 /** * Evaluates the given postfix expression. * * @param expr Arithmetic expression in postfix notation * @return The value of the evaluated expression * @throws ExpressionException if the expression is wrong */ public static int evaluate(String expr) throws ExpressionException { expr = expr.trim(); String[] tokens = expr.split("\\s+"); if(expr.matches("(\\+)|(\\-)|(\\*)|(\\/)")){ throw new ExpressionException(""); } LinkedList stack = new LinkedList<>(); for(String token: tokens) { if(isInteger(token)) { int number = Integer.parseInt(token); stack.push(number); } else if(isOperator(token)) { String operator = token; int b = stack.pop(); int a = stack.pop(); if(token.equals("+")){ stack.push(a+b); } else if (token.equals("-")){ stack.push(a-b); } else if(token.equals("/")){ if( b == 0){ throw new ExpressionException(""); } stack.push(a/b); } else if(token.equals("*")){ stack.push(a*b); } } else { throw new ExpressionException(""); } } if(stack.size() != 1){ throw new ExpressionException(""); } int result = stack.pop(); if(stack.isEmpty()) { throw new ExpressionException(""); } return result; } /** * Returns true if s is an operator. * * A word of caution on using the String.matches method: it returns true * if and only if the whole given string matches the regex. Therefore * using the regex "[0-9]" is equivalent to "^[0-9]$". * * An operator is one of '+', '-', '*', '/'. */ private static boolean isOperator(String s) { return s.matches("[-+*/]"); } /** * Returns true if s is an integer. * * A word of caution on using the String.matches method: it returns true * if and only if the whole given string matches the regex. Therefore * using the regex "[0-9]" is equivalent to "^[0-9]$". * * We accept two types of integers: * * - the first type consists of an optional '-' * followed by a non-zero digit * followed by zero or more digits, * * - the second type consists of an optional '-' * followed by a single '0'. */ private static boolean isInteger(String s) { return s.matches("(((\\-)*?[1-9](\\d+)*)|(\\-)*?0)"); } }

JUNIT test classs

import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; import java.util.Arrays; /** * Test class for Postfix * */ public class PostfixTest { @Rule public Timeout globalTimeout = Timeout.seconds(5); @Test public void evaluateExceptionWhenExprContainsTooFewOperands() { String[] expressions = {"1 +", " 1 2 + +"}; assertExpressionExceptionOnAll(expressions); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!