SlideShare a Scribd company logo
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack's top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack's top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with ','
return "";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(" "+
"******************************************************* "+
"Sample Expected output: "+
" "+
"OK: stack is empty "+
"Push 3 data: 10, 30, 50 "+
"Print stack [50,30,10,] "+
"OK: stack size is 3 "+
"OK: peek stack top is 50 "+
"OK: stack is not empty "+
"Pop 2 data: 50, 30 "+
"Print stack [30,10,] "+
"Print stack [10,] "+
"OK: stack pop data is 30 "+
"Clear stack "+
"Print stack [] "+
" "+
"*******************************************************");
System.out.println(" Your Test output: ");
StackInterface s = new SimpleLinkedStack();
if (s.empty())
System.out.println("OK: stack is empty");
else
System.out.println("Error: stack is not empty");
s.push(10);
s.push(30);
s.push(50);
System.out.println("Push 3 data: 10, 30, 50");
System.out.println("Print stack " + s);
if (s.size() == 3)
System.out.println("OK: stack size is 3");
else
System.out.println("Error: stack size is " + s.size());
if (s.peek() == 50)
System.out.println("OK: peek stack top is 50");
else
System.out.println("Error: peek stack top is " + s.size());
if (!s.empty())
System.out.println("OK: stack is not empty");
else
System.out.println("Error: stack is empty");
System.out.println("Pop 2 data: 50, 30");
s.pop();
System.out.println("Print stack " + s);
int data=s.pop();
System.out.println("Print stack " + s);
if (data == 30)
System.out.println("OK: stack pop data is 30");
else
System.out.println("Error: stack pop data is " + data);
System.out.println("Clear stack");
s.clear();
System.out.println("Print stack " + s);
}
} // end Stack
LispExpressionEception
/*****************************************************************************
*******
*
* Do not modify this file.
*
* LispExpressionException
*
* It is used by LispExpressionEvaluator
*
*****************************************************************************
********/
package PJ2;
public class LispExpressionException extends RuntimeException
{
public LispExpressionException()
{
this("");
}
public LispExpressionException(String errorMsg)
{
super(errorMsg);
}
}
LispExpressionEvaluator
/*****************************************************************************
*******
*
* CSC220 Programming Project#2
*
* Specification:
*
* Taken from Project 7, Chapter 5, Page 178
* I have modified specification and requirements of this project
*
* Ref: http://www.gigamonkeys.com/book/ (see chap. 10)
*
* In the language Lisp, each of the four basic arithmetic operators appears
* before an arbitrary number of operands, which are separated by spaces.
* The resulting expression is enclosed in parentheses. The operators behave
* as follows:
*
* (+ a b c ...) returns the sum of all the operands, and (+ a) returns a.
*
* (- a b c ...) returns a - b - c - ..., and (- a) returns -a.
*
* (* a b c ...) returns the product of all the operands, and (* a) returns a.
*
* (/ a b c ...) returns a / b / c / ..., and (/ a) returns 1/a.
*
* Note: + * - / must have at least one operand
*
* You can form larger arithmetic expressions by combining these basic
* expressions using a fully parenthesized prefix notation.
* For example, the following is a valid Lisp expression:
*
* (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))
*
* This expression is evaluated successively as follows:
*
* (+ (- 6) (* 2 3 4) (/ 3 1 -2) (+ 1))
* (+ -6 24 -1.5 1.0)
* 17.5
*
* Requirements:
*
* - Design and implement an algorithm that uses SimpleLinkedStack class to evaluate a
* valid Lisp expression composed of the four basic operators and integer values.
* - Valid tokens in an expression are '(',')','+','-','*','/',and positive integers (>=0)
* - Display result as floting point number with at 2 decimal places
* - Negative number is not a valid "input" operand, e.g. (+ -2 3)
* However, you may create a negative number using parentheses, e.g. (+ (-2)3)
* - There may be any number of blank spaces, >= 0, in between tokens
* Thus, the following expressions are valid:
* (+ (-6)3)
* (/(+20 30))
*
* - Must use StackInterface and SimpleLinkedStack in this project.
(*** DO NOT USE Java API Stack class ***)
* - Must throw LispExpressionException to indicate errors
* - Must not add new or modify existing data fields
* - Must implement methods in SimpleLinkedStack class.
* - Must implement these methods in LispExpressionEvaluator class:
*
* public LispExpressionEvaluator()
* public LispExpressionEvaluator(String inputExpression)
* public void reset(String inputExpression)
* public double evaluate()
* private void solveCurrentParenthesisOperation()
*
* - You may add new private methods
*
*****************************************************************************
********/
package PJ2;
import java.util.*;
public class LispExpressionEvaluator
{
// Current input Lisp expression
private String currentExpression;
// Main expression stack, see algorithm in evaluate()
private StackInterface allTokensStack;
private StackInterface currentOperandsStack;
// default constructor
// set currentExpression to ""
// create stack objects
public LispExpressionEvaluator()
{
// add statements
}
// constructor with an input expression
// set currentExpression to inputExpression
// create stack objects
public LispExpressionEvaluator(String inputExpression)
{
// add statements
}
// set currentExpression to inputExpression
// clear stack objects
public void reset(String inputExpression)
{
// add statements
}
// This function evaluates current operator with its operands
// See complete algorithm in evaluate()
//
// Main Steps:
// Pop operands from allTokensStack and push them onto
// currentOperandsStack until you find an operator
// Apply the operator to the operands on currentOperandsStack
// Push the result into allTokensStack
//
private void solveCurrentParenthesisOperation()
{
// add statements
}
/**
* This funtion evaluates current Lisp expression in currentExpression
* It return result of the expression
*
* The algorithm:
*
* Step 1 Scan the tokens in the string.
* Step 2 If you see an operand, push operand object onto the allTokensStack
* Step 3 If you see "(", next token should be an operator
* Step 4 If you see an operator, push operator object onto the allTokensStack
* Step 5 If you see ")" // steps in solveCurrentParenthesisOperation() :
* Step 6 Pop operands and push them onto currentOperandsStack
* until you find an operator
* Step 7 Apply the operator to the operands on currentOperandsStack
* Step 8 Push the result into allTokensStack
* Step 9 If you run out of tokens, the value on the top of allTokensStack is
* is the result of the expression.
*/
public double evaluate()
{
// only outline is given...
// you need to add statements/local variables
// you may delete or modify any statements in this method
// use scanner to tokenize currentExpression
Scanner currentExpressionScanner = new Scanner(currentExpression);
// Use zero or more white space as delimiter,
// which breaks the string into single character tokens
currentExpressionScanner = currentExpressionScanner.useDelimiter("s*");
// Step 1: Scan the tokens in the string.
while (currentExpressionScanner.hasNext())
{
// Step 2: If you see an operand, push operand object onto the allTokensStack
if (currentExpressionScanner.hasNextInt())
{
// This force scanner to grab all of the digits
// Otherwise, it will just get one char
String dataString = currentExpressionScanner.findInLine("d+");
// more ...
}
else
{
// Get next token, only one char in string token
String aToken = currentExpressionScanner.next();
//System.out.println("Other: " + aToken);
char item = aToken.charAt(0);
switch (item)
{
// Step 3: If you see "(", next token shoube an operator
// Step 4: If you see an operator, push operator object onto the allTokensStack
// Step 5: If you see ")" // steps in solveCurrentParenthesisOperation() :
default: // error
throw new LispExpressionException(item + " is not a legal expression operator");
} // end switch
} // end else
} // end while
// Step 9: If you run out of tokens, the value on the top of allTokensStack is
// is the result of the expression.
//
// return result
return 0.0; // return the correct result
}
//====================================================================
=
// DO NOT MODIFY ANY STATEMENTS BELOW
//====================================================================
=
// This static method is used by main() only
private static void evaluateExprTest(String s, LispExpressionEvaluator expr, String expect)
{
Double result;
System.out.println("Expression " + s);
System.out.printf("Expected result : %s ", expect);
expr.reset(s);
try {
result = expr.evaluate();
System.out.printf("Evaluated result : %.2f ", result);
}
catch (LispExpressionException e) {
System.out.println("Evaluated result :"+e);
}
System.out.println("-----------------------------");
}
// define few test cases, exception may happen
public static void main (String args[])
{
LispExpressionEvaluator expr= new LispExpressionEvaluator();
//expr.setDebug();
String test1 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))";
String test2 = "(+ (- 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)) (+ 0))";
String test3 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 1) (- 2 1 ))(* 1))";
String test4 = "(+ (/2)(+ 1))";
String test5 = "(+ (/2 3 0))";
String test6 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 3) (- 2 1 ))))";
String test7 = "(+ (*))";
String test8 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ ))";
evaluateExprTest(test1, expr, "17.50");
evaluateExprTest(test2, expr, "-378.12");
evaluateExprTest(test3, expr, "4.50");
evaluateExprTest(test4, expr, "1.5");
evaluateExprTest(test5, expr, "Infinity or LispExpressionException");
evaluateExprTest(test6, expr, "LispExpressionException");
evaluateExprTest(test7, expr, "LispExpressionException");
evaluateExprTest(test8, expr, "LispExpressionException");
}
} You need to implement (15%) 85%) simpleLinkedStack. Java LISpExpressionEvaluator.java
See proiect reauirements in LispExpressionEvaluator.java Upload single zip file containing
above 2 files to ilearn Use PJ2 Test.iava to test correctness of vour program Compile programs
(v ou are in directory containing Readme file): javac PJ2/*. java javac *. java C *.java Run
programs (vou are in directory containing Readme file): // Run main() method tests in
LispExpressionEvaluator java PJ2.SimpleLinkedStack java PJ2.LispExpressionEvaluator // Run
main test program iava PJ2 Test
Solution
PROGRAM CODE:
SimpleLinkedStack.java
package PJ2;
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// initializing the data members
this.topNode = null;
this.count = 0;
} // end default constructor
public void push(T newData)
{
// checking if topnode is null
if(topNode == null)
{
topNode = new Node(newData);
topNode.next = null;
}
else
{
//if topnode is not null, store topnode in a new node and add the data to topnode and link
next to the newnode
Node node = new Node(newData);
node.next = topNode;
topNode = node;
}
} // end push
public T peek()
{
// return the topnode's data
if(topNode != null)
return topNode.data;
else return null;
} // end peek
public T pop()
{
// remove the topnode's data
T deletedData = null;
if(topNode != null)
{
deletedData = topNode.data;
Node newnode = topNode.next;
if(newnode != null)
{
topNode.data = newnode.data;
topNode.next = newnode.next;
}
else
{
topNode = null;
}
}
return deletedData;
} // end pop
public boolean empty()
{
// checking if the stack is empty
if(topNode==null)
return true;
else
return false;
} // end empty
public int size()
{
// add stataments
int size = 0;
Node newnode = topNode;
while(newnode!=null)
{
size++;
newnode = newnode.next;
}
return size;
} // end isEmpty
public void clear()
{
// clearing the whole stack
topNode = null;
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with ','
String value = "[";
Node newnode = topNode;
int counter = 0;
while(counter s = new SimpleLinkedStack();
if (s.empty())
System.out.println("OK: stack is empty");
else
System.out.println("Error: stack is not empty");
s.push(10);
s.push(30);
s.push(50);
System.out.println("Push 3 data: 10, 30, 50");
System.out.println("Print stack " + s);
if (s.size() == 3)
System.out.println("OK: stack size is 3");
else
System.out.println("Error: stack size is " + s.size());
if (s.peek() == 50)
System.out.println("OK: peek stack top is 50");
else
System.out.println("Error: peek stack top is " + s.size());
if (!s.empty())
System.out.println("OK: stack is not empty");
else
System.out.println("Error: stack is empty");
System.out.println("Pop 2 data: 50, 30");
s.pop();
System.out.println("Print stack " + s);
int data=s.pop();
System.out.println("Print stack " + s);
if (data == 30)
System.out.println("OK: stack pop data is 30");
else
System.out.println("Error: stack pop data is " + data);
System.out.println("Clear stack");
s.clear();
System.out.println("Print stack " + s);
}
} // end Stack
OUTPUT:
*******************************************************
Sample Expected output:
OK: stack is empty
Push 3 data: 10, 30, 50
Print stack [50,30,10,]
OK: stack size is 3
OK: peek stack top is 50
OK: stack is not empty
Pop 2 data: 50, 30
Print stack [30,10,]
Print stack [10,]
OK: stack pop data is 30
Clear stack
Print stack []
*******************************************************
Your Test output:
OK: stack is empty
Push 3 data: 10, 30, 50
Print stack [50,30,10,]
OK: stack size is 3
OK: peek stack top is 50
OK: stack is not empty
Pop 2 data: 50, 30
Print stack [30,10,]
Print stack [10,]
OK: stack pop data is 30
Clear stack
Print stack []
PROGRAM CODE:
LispExpressionEvaluator.java
/*****************************************************************************
*******
*
* CSC220 Programming Project#2
*
* Specification:
*
* Taken from Project 7, Chapter 5, Page 178
* I have modified specification and requirements of this project
*
* Ref: http://www.gigamonkeys.com/book/ (see chap. 10)
*
* In the language Lisp, each of the four basic arithmetic operators appears
* before an arbitrary number of operands, which are separated by spaces.
* The resulting expression is enclosed in parentheses. The operators behave
* as follows:
*
* (+ a b c ...) returns the sum of all the operands, and (+ a) returns a.
*
* (- a b c ...) returns a - b - c - ..., and (- a) returns -a.
*
* (* a b c ...) returns the product of all the operands, and (* a) returns a.
*
* (/ a b c ...) returns a / b / c / ..., and (/ a) returns 1/a.
*
* Note: + * - / must have at least one operand
*
* You can form larger arithmetic expressions by combining these basic
* expressions using a fully parenthesized prefix notation.
* For example, the following is a valid Lisp expression:
*
* (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))
*
* This expression is evaluated successively as follows:
*
* (+ (- 6) (* 2 3 4) (/ 3 1 -2) (+ 1))
* (+ -6 24 -1.5 1.0)
* 17.5
*
* Requirements:
*
* - Design and implement an algorithm that uses SimpleLinkedStack class to evaluate a
* valid Lisp expression composed of the four basic operators and integer values.
* - Valid tokens in an expression are '(',')','+','-','*','/',and positive integers (>=0)
* - Display result as floting point number with at 2 decimal places
* - Negative number is not a valid "input" operand, e.g. (+ -2 3)
* However, you may create a negative number using parentheses, e.g. (+ (-2)3)
* - There may be any number of blank spaces, >= 0, in between tokens
* Thus, the following expressions are valid:
* (+ (-6)3)
* (/(+20 30))
*
* - Must use StackInterface and SimpleLinkedStack in this project.
(*** DO NOT USE Java API Stack class ***)
* - Must throw LispExpressionException to indicate errors
* - Must not add new or modify existing data fields
* - Must implement methods in SimpleLinkedStack class.
* - Must implement these methods in LispExpressionEvaluator class:
*
* public LispExpressionEvaluator()
* public LispExpressionEvaluator(String inputExpression)
* public void reset(String inputExpression)
* public double evaluate()
* private void solveCurrentParenthesisOperation()
*
* - You may add new private methods
*
*****************************************************************************
********/
package PJ2;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class LispExpressionEvaluator
{
// Current input Lisp expression
private String currentExpression;
// Main expression stack, see algorithm in evaluate()
private StackInterface allTokensStack;
private StackInterface currentOperandsStack;
// default constructor
// set currentExpression to ""
// create stack objects
public LispExpressionEvaluator()
{
currentExpression = "";
allTokensStack = new SimpleLinkedStack();
currentOperandsStack = new SimpleLinkedStack();
}
// constructor with an input expression
// set currentExpression to inputExpression
// create stack objects
public LispExpressionEvaluator(String inputExpression)
{
currentExpression = inputExpression;
allTokensStack = new SimpleLinkedStack();
currentOperandsStack = new SimpleLinkedStack();
}
// set currentExpression to inputExpression
// clear stack objects
public void reset(String inputExpression)
{
currentExpression = inputExpression;
allTokensStack.clear();
currentOperandsStack.clear();
}
// This function evaluates current operator with its operands
// See complete algorithm in evaluate()
//
// Main Steps:
// Pop operands from allTokensStack and push them onto
// currentOperandsStack until you find an operator
// Apply the operator to the operands on currentOperandsStack
// Push the result into allTokensStack
//
private void solveCurrentParenthesisOperation()
{
try{
String token = allTokensStack.pop().toString();
while(!token.equals("*") && !token.equals("/") && !token.equals("+") &&
!token.equals("-"))
{
currentOperandsStack.push(Double.valueOf(token));
token = allTokensStack.pop().toString();
}
//System.out.println("operands: " + currentOperandsStack);
//System.out.println("operator: " + token);
Double result = currentOperandsStack.pop();;
if(token.equals("*"))
{
while(!currentOperandsStack.empty())
{
result = result * currentOperandsStack.pop();
}
}
else if(token.equals("+"))
{
while(!currentOperandsStack.empty())
{
result = result + currentOperandsStack.pop();
}
}
else if(token.equals("-"))
{
if(currentOperandsStack.size() == 0)
{
result = -1 * result;
}
else
{
while(!currentOperandsStack.empty())
{
result = result - currentOperandsStack.pop();
}
}
}
else if(token.equals("/"))
{
if(currentOperandsStack.size() == 0)
{
result = 1/result;
}
else
{
while(!currentOperandsStack.empty())
{
result = result / currentOperandsStack.pop();
}
}
}
//System.out.println("my result: " + result);
//rounding to two decimal value
allTokensStack.push(result);
}
catch(Exception e)
{
throw new LispExpressionException("LispExpressionException");
}
}
/**
* This funtion evaluates current Lisp expression in currentExpression
* It return result of the expression
*
* The algorithm:
*
* Step 1 Scan the tokens in the string.
* Step 2 If you see an operand, push operand object onto the allTokensStack
* Step 3 If you see "(", next token should be an operator
* Step 4 If you see an operator, push operator object onto the allTokensStack
* Step 5 If you see ")" // steps in solveCurrentParenthesisOperation() :
* Step 6 Pop operands and push them onto currentOperandsStack
* until you find an operator
* Step 7 Apply the operator to the operands on currentOperandsStack
* Step 8 Push the result into allTokensStack
* Step 9 If you run out of tokens, the value on the top of allTokensStack is
* is the result of the expression.
*/
public double evaluate() throws LispExpressionException
{
// only outline is given...
// you need to add statements/local variables
// you may delete or modify any statements in this method
double result = 0;
// use scanner to tokenize currentExpression
Scanner currentExpressionScanner = new Scanner(currentExpression);
// Use zero or more white space as delimiter,
// which breaks the string into single character tokens
currentExpressionScanner = currentExpressionScanner.useDelimiter("s*");
// Step 1: Scan the tokens in the string.
while (currentExpressionScanner.hasNext())
{
// Step 2: If you see an operand, push operand object onto the allTokensStack
if (currentExpressionScanner.hasNextInt())
{
// This force scanner to grab all of the digits
// Otherwise, it will just get one char
String dataString = currentExpressionScanner.findInLine("d+");
//System.out.println(dataString);
allTokensStack.push(Double.valueOf(dataString));
// more ...
}
else
{
// Get next token, only one char in string token
String aToken = currentExpressionScanner.next();
//System.out.println("Other: " + aToken);
char item = aToken.charAt(0);
switch (item)
{
// Step 3: If you see "(", next token shoube an operator
// Step 4: If you see an operator, push operator object onto the allTokensStack
// Step 5: If you see ")" // steps in solveCurrentParenthesisOperation() :
case '(': break;
case ')' : solveCurrentParenthesisOperation();
break;
case '*' :
case '+' :
case '-' :
case '/' : allTokensStack.push(item);
break;
default: // error
throw new LispExpressionException(item + " is not a legal expression operator");
} // end switch
} // end else
} // end while
// Step 9: If you run out of tokens, the value on the top of allTokensStack is
// is the result of the expression.
//
// return result
try
{
result = (Double) allTokensStack.peek();
}
catch(Exception e)
{
throw new LispExpressionException("LispExpressionException");
}
return result;
}
//====================================================================
=
// DO NOT MODIFY ANY STATEMENTS BELOW
//====================================================================
=
// This static method is used by main() only
private static void evaluateExprTest(String s, LispExpressionEvaluator expr, String expect)
{
Double result;
System.out.println("Expression " + s);
System.out.printf("Expected result : %s ", expect);
expr.reset(s);
try {
result = expr.evaluate();
System.out.printf("Evaluated result : %.2f ", result);
}
catch (LispExpressionException e) {
System.out.println("Evaluated result :"+e);
}
System.out.println("-----------------------------");
}
// define few test cases, exception may happen
public static void main (String args[])
{
LispExpressionEvaluator expr= new LispExpressionEvaluator();
//expr.setDebug();
String test1 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))";
String test2 = "(+ (- 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)) (+ 0))";
String test3 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 1) (- 2 1 ))(* 1))";
String test4 = "(+ (/2)(+ 1))";
String test5 = "(+ (/2 3 0))";
String test6 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 3) (- 2 1 ))))";
String test7 = "(+ (*))";
String test8 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ ))";
evaluateExprTest(test1, expr, "17.50");
evaluateExprTest(test2, expr, "-378.12");
evaluateExprTest(test3, expr, "4.50");
evaluateExprTest(test4, expr, "1.5");
evaluateExprTest(test5, expr, "Infinity or LispExpressionException");
evaluateExprTest(test6, expr, "LispExpressionException");
evaluateExprTest(test7, expr, "LispExpressionException");
evaluateExprTest(test8, expr, "LispExpressionException");
}
}
OUTPUT:
Expression (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))
Expected result : 17.50
Evaluated result : 17.50
-----------------------------
Expression (+ (- 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)) (+ 0))
Expected result : -378.12
Evaluated result : -378.12
-----------------------------
Expression (+ (/ 2) (* 2) (/ (+ 1) (+ 1) (- 2 1 ))(* 1))
Expected result : 4.50
Evaluated result : 4.50
-----------------------------
Expression (+ (/2)(+ 1))
Expected result : 1.5
Evaluated result : 1.50
-----------------------------
Expression (+ (/2 3 0))
Expected result : Infinity or LispExpressionException
Evaluated result : Infinity
-----------------------------
Expression (+ (/ 2) (* 2) (/ (+ 1) (+ 3) (- 2 1 ))))
Expected result : LispExpressionException
Evaluated result :PJ2.LispExpressionException: LispExpressionException
-----------------------------
Expression (+ (*))
Expected result : LispExpressionException
Evaluated result :PJ2.LispExpressionException: LispExpressionException
-----------------------------
Expression (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ ))
Expected result : LispExpressionException
Evaluated result :PJ2.LispExpressionException: LispExpressionException
-----------------------------

More Related Content

Similar to StackInterface An interface for the ADT stack. Do not modif.pdf (20)

DOCX
ContentsCOSC 2436 – LAB4TITLE .............................docx
dickonsondorris
 
PDF
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
PPT
Data Structure and Algorithms Stacks
ManishPrajapati78
 
PPT
Stack Operation In Data Structure
DivyeshKumar Jagatiya
 
DOCX
----------Evaluator-java---------------- package evaluator- import j.docx
Adamq0DJonese
 
PPTX
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
PDF
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
PPTX
Ch05_Stacks implementation in data structures.pptx
rexwilde3095
 
PDF
Java Code The traditional way to deal with these in Parsers is the .pdf
stopgolook
 
PDF
Data structuresUsing java language and develop a prot.pdf
armyshoes
 
PDF
Data structure lab manual
nikshaikh786
 
PPTX
Project on stack Data structure
Soham Nanekar
 
PPTX
5.stack
Chandan Singh
 
PPT
Unit 3 stack
kalyanineve
 
PPTX
5.-Stacks.pptx
iloveyoucarlo0923
 
PPTX
DS UNIT1_STACKS.pptx
VeerannaKotagi1
 
PDF
I need help implementing a Stack with this java programming assignme.pdf
sauravmanwanicp
 
PPSX
Stack
Seema Sharma
 
PDF
Ds stack 03
MuhammadZubair568
 
PDF
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 
ContentsCOSC 2436 – LAB4TITLE .............................docx
dickonsondorris
 
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
Data Structure and Algorithms Stacks
ManishPrajapati78
 
Stack Operation In Data Structure
DivyeshKumar Jagatiya
 
----------Evaluator-java---------------- package evaluator- import j.docx
Adamq0DJonese
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
Ch05_Stacks implementation in data structures.pptx
rexwilde3095
 
Java Code The traditional way to deal with these in Parsers is the .pdf
stopgolook
 
Data structuresUsing java language and develop a prot.pdf
armyshoes
 
Data structure lab manual
nikshaikh786
 
Project on stack Data structure
Soham Nanekar
 
5.stack
Chandan Singh
 
Unit 3 stack
kalyanineve
 
5.-Stacks.pptx
iloveyoucarlo0923
 
DS UNIT1_STACKS.pptx
VeerannaKotagi1
 
I need help implementing a Stack with this java programming assignme.pdf
sauravmanwanicp
 
Ds stack 03
MuhammadZubair568
 
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 

More from ARCHANASTOREKOTA (20)

PDF
Please help! Computer Science C++ programming code needed.Thank yo.pdf
ARCHANASTOREKOTA
 
PDF
Please Answer, will rate! Exercise 1 - Classifying financial stateme.pdf
ARCHANASTOREKOTA
 
PDF
Need 2 -3 paragraphConsidering the aesthetics of the late 19th cen.pdf
ARCHANASTOREKOTA
 
PDF
Match each statement to the most appropriate choices. More than one .pdf
ARCHANASTOREKOTA
 
PDF
List three sources of variability in material properties. If that va.pdf
ARCHANASTOREKOTA
 
PDF
Need the fill in the blank questions answeredSolution1) CamboB.pdf
ARCHANASTOREKOTA
 
PDF
making and testing a prediction suppose that after 22 months, gupp.pdf
ARCHANASTOREKOTA
 
PDF
Life is wholly dependent on water. List and discuss two reasons why .pdf
ARCHANASTOREKOTA
 
PDF
John Rawls argued that societys goal should be to lessen the welfar.pdf
ARCHANASTOREKOTA
 
PDF
In Exercises 19-24, find the volume of the solid generated by revolvi.pdf
ARCHANASTOREKOTA
 
PDF
In which step of meiosis, the members of tetra separate Solutio.pdf
ARCHANASTOREKOTA
 
PDF
Identify the distinguishing characteristics of member of Phylum Cnid.pdf
ARCHANASTOREKOTA
 
PDF
If most evolutionary change occurs during and immediately after spec.pdf
ARCHANASTOREKOTA
 
PDF
Imagine that someone picking up roses in a garden gets a scratch fro.pdf
ARCHANASTOREKOTA
 
PDF
I need help working out this question . woman has normal vision al.pdf
ARCHANASTOREKOTA
 
PDF
I have a Programming is Binary Tree Search (BTS) for strings with po.pdf
ARCHANASTOREKOTA
 
PDF
How is ATP produced in mammalian cells under aerobic conditions1..pdf
ARCHANASTOREKOTA
 
PDF
How con osmosis work for and against homeostasis How do osmosis .pdf
ARCHANASTOREKOTA
 
PDF
Enzymes and KE. Whats the relationship in terms of substrate mo.pdf
ARCHANASTOREKOTA
 
PDF
Explain membranes. Include the definition and name the four types an.pdf
ARCHANASTOREKOTA
 
Please help! Computer Science C++ programming code needed.Thank yo.pdf
ARCHANASTOREKOTA
 
Please Answer, will rate! Exercise 1 - Classifying financial stateme.pdf
ARCHANASTOREKOTA
 
Need 2 -3 paragraphConsidering the aesthetics of the late 19th cen.pdf
ARCHANASTOREKOTA
 
Match each statement to the most appropriate choices. More than one .pdf
ARCHANASTOREKOTA
 
List three sources of variability in material properties. If that va.pdf
ARCHANASTOREKOTA
 
Need the fill in the blank questions answeredSolution1) CamboB.pdf
ARCHANASTOREKOTA
 
making and testing a prediction suppose that after 22 months, gupp.pdf
ARCHANASTOREKOTA
 
Life is wholly dependent on water. List and discuss two reasons why .pdf
ARCHANASTOREKOTA
 
John Rawls argued that societys goal should be to lessen the welfar.pdf
ARCHANASTOREKOTA
 
In Exercises 19-24, find the volume of the solid generated by revolvi.pdf
ARCHANASTOREKOTA
 
In which step of meiosis, the members of tetra separate Solutio.pdf
ARCHANASTOREKOTA
 
Identify the distinguishing characteristics of member of Phylum Cnid.pdf
ARCHANASTOREKOTA
 
If most evolutionary change occurs during and immediately after spec.pdf
ARCHANASTOREKOTA
 
Imagine that someone picking up roses in a garden gets a scratch fro.pdf
ARCHANASTOREKOTA
 
I need help working out this question . woman has normal vision al.pdf
ARCHANASTOREKOTA
 
I have a Programming is Binary Tree Search (BTS) for strings with po.pdf
ARCHANASTOREKOTA
 
How is ATP produced in mammalian cells under aerobic conditions1..pdf
ARCHANASTOREKOTA
 
How con osmosis work for and against homeostasis How do osmosis .pdf
ARCHANASTOREKOTA
 
Enzymes and KE. Whats the relationship in terms of substrate mo.pdf
ARCHANASTOREKOTA
 
Explain membranes. Include the definition and name the four types an.pdf
ARCHANASTOREKOTA
 
Ad

Recently uploaded (20)

PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Ad

StackInterface An interface for the ADT stack. Do not modif.pdf

  • 1. StackInterface /** An interface for the ADT stack. Do not modify this file */ package PJ2; public interface StackInterface { /** Gets the current number of data in this stack. @return the integer number of entries currently in the stack*/ public int size(); /** Adds a new data to the top of this stack. @param aData an object to be added to the stack */ public void push(T aData); /** Removes and returns this stack's top data. @return either the object at the top of the stack or, if the stack is empty before the operation, null */ public T pop(); /** Retrieves this stack's top data. @return either the data at the top of the stack or null if the stack is empty */ public T peek(); /** Detects whether this stack is empty. @return true if the stack is empty */ public boolean empty(); /** Removes all data from this stack */ public void clear(); } // end StackInterface SimpleLinkedStack.java /** A class of stacks whose entries are stored in a chain of nodes.
  • 2. Implement all methods in SimpleLinkedStack class using the inner Node class. Main Reference : text book or class notes Do not change or add data fields Do not add new methods You may access Node object fields directly, i.e. data and next */ package PJ2; public class SimpleLinkedStack implements StackInterface { // Data fields private Node topNode; // references the first node in the chain private int count; // number of data in this stack public SimpleLinkedStack() { // add stataments } // end default constructor public void push(T newData) { // add stataments } // end push public T peek() { // add stataments return null; } // end peek public T pop() { // add stataments return null; } // end pop public boolean empty() {
  • 3. // add stataments return false; } // end empty public int size() { // add stataments return -1; } // end isEmpty public void clear() { // add stataments } // end clear public String toString() { // add stataments // note: data class in stack must implement toString() method // return a list of data in Stack, separate them with ',' return ""; } /**************************************************** private inner node class Do not modify this class!! you may access data and next directly ***************************************************/ private class Node { private T data; // entry in list private Node next; // link to next node private Node (T dataPortion) { data = dataPortion; next = null; // set next to NULL } // end constructor private Node (T dataPortion, Node nextNode) {
  • 4. data = dataPortion; next = nextNode; // set next to refer to nextNode } // end constructor } // end Node /**************************************************** Do not modify: Stack test ****************************************************/ public static void main (String args[]) { System.out.println(" "+ "******************************************************* "+ "Sample Expected output: "+ " "+ "OK: stack is empty "+ "Push 3 data: 10, 30, 50 "+ "Print stack [50,30,10,] "+ "OK: stack size is 3 "+ "OK: peek stack top is 50 "+ "OK: stack is not empty "+ "Pop 2 data: 50, 30 "+ "Print stack [30,10,] "+ "Print stack [10,] "+ "OK: stack pop data is 30 "+ "Clear stack "+ "Print stack [] "+ " "+ "*******************************************************"); System.out.println(" Your Test output: "); StackInterface s = new SimpleLinkedStack(); if (s.empty()) System.out.println("OK: stack is empty"); else System.out.println("Error: stack is not empty"); s.push(10); s.push(30);
  • 5. s.push(50); System.out.println("Push 3 data: 10, 30, 50"); System.out.println("Print stack " + s); if (s.size() == 3) System.out.println("OK: stack size is 3"); else System.out.println("Error: stack size is " + s.size()); if (s.peek() == 50) System.out.println("OK: peek stack top is 50"); else System.out.println("Error: peek stack top is " + s.size()); if (!s.empty()) System.out.println("OK: stack is not empty"); else System.out.println("Error: stack is empty"); System.out.println("Pop 2 data: 50, 30"); s.pop(); System.out.println("Print stack " + s); int data=s.pop(); System.out.println("Print stack " + s); if (data == 30) System.out.println("OK: stack pop data is 30"); else System.out.println("Error: stack pop data is " + data); System.out.println("Clear stack"); s.clear(); System.out.println("Print stack " + s); } } // end Stack LispExpressionEception /***************************************************************************** ******* * * Do not modify this file. * * LispExpressionException
  • 6. * * It is used by LispExpressionEvaluator * ***************************************************************************** ********/ package PJ2; public class LispExpressionException extends RuntimeException { public LispExpressionException() { this(""); } public LispExpressionException(String errorMsg) { super(errorMsg); } } LispExpressionEvaluator /***************************************************************************** ******* * * CSC220 Programming Project#2 * * Specification: * * Taken from Project 7, Chapter 5, Page 178 * I have modified specification and requirements of this project * * Ref: http://www.gigamonkeys.com/book/ (see chap. 10) * * In the language Lisp, each of the four basic arithmetic operators appears * before an arbitrary number of operands, which are separated by spaces. * The resulting expression is enclosed in parentheses. The operators behave * as follows: * * (+ a b c ...) returns the sum of all the operands, and (+ a) returns a.
  • 7. * * (- a b c ...) returns a - b - c - ..., and (- a) returns -a. * * (* a b c ...) returns the product of all the operands, and (* a) returns a. * * (/ a b c ...) returns a / b / c / ..., and (/ a) returns 1/a. * * Note: + * - / must have at least one operand * * You can form larger arithmetic expressions by combining these basic * expressions using a fully parenthesized prefix notation. * For example, the following is a valid Lisp expression: * * (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1)) * * This expression is evaluated successively as follows: * * (+ (- 6) (* 2 3 4) (/ 3 1 -2) (+ 1)) * (+ -6 24 -1.5 1.0) * 17.5 * * Requirements: * * - Design and implement an algorithm that uses SimpleLinkedStack class to evaluate a * valid Lisp expression composed of the four basic operators and integer values. * - Valid tokens in an expression are '(',')','+','-','*','/',and positive integers (>=0) * - Display result as floting point number with at 2 decimal places * - Negative number is not a valid "input" operand, e.g. (+ -2 3) * However, you may create a negative number using parentheses, e.g. (+ (-2)3) * - There may be any number of blank spaces, >= 0, in between tokens * Thus, the following expressions are valid: * (+ (-6)3) * (/(+20 30)) * * - Must use StackInterface and SimpleLinkedStack in this project. (*** DO NOT USE Java API Stack class ***)
  • 8. * - Must throw LispExpressionException to indicate errors * - Must not add new or modify existing data fields * - Must implement methods in SimpleLinkedStack class. * - Must implement these methods in LispExpressionEvaluator class: * * public LispExpressionEvaluator() * public LispExpressionEvaluator(String inputExpression) * public void reset(String inputExpression) * public double evaluate() * private void solveCurrentParenthesisOperation() * * - You may add new private methods * ***************************************************************************** ********/ package PJ2; import java.util.*; public class LispExpressionEvaluator { // Current input Lisp expression private String currentExpression; // Main expression stack, see algorithm in evaluate() private StackInterface allTokensStack; private StackInterface currentOperandsStack; // default constructor // set currentExpression to "" // create stack objects public LispExpressionEvaluator() { // add statements } // constructor with an input expression // set currentExpression to inputExpression // create stack objects public LispExpressionEvaluator(String inputExpression) {
  • 9. // add statements } // set currentExpression to inputExpression // clear stack objects public void reset(String inputExpression) { // add statements } // This function evaluates current operator with its operands // See complete algorithm in evaluate() // // Main Steps: // Pop operands from allTokensStack and push them onto // currentOperandsStack until you find an operator // Apply the operator to the operands on currentOperandsStack // Push the result into allTokensStack // private void solveCurrentParenthesisOperation() { // add statements } /** * This funtion evaluates current Lisp expression in currentExpression * It return result of the expression * * The algorithm: * * Step 1 Scan the tokens in the string. * Step 2 If you see an operand, push operand object onto the allTokensStack * Step 3 If you see "(", next token should be an operator * Step 4 If you see an operator, push operator object onto the allTokensStack * Step 5 If you see ")" // steps in solveCurrentParenthesisOperation() : * Step 6 Pop operands and push them onto currentOperandsStack * until you find an operator * Step 7 Apply the operator to the operands on currentOperandsStack * Step 8 Push the result into allTokensStack
  • 10. * Step 9 If you run out of tokens, the value on the top of allTokensStack is * is the result of the expression. */ public double evaluate() { // only outline is given... // you need to add statements/local variables // you may delete or modify any statements in this method // use scanner to tokenize currentExpression Scanner currentExpressionScanner = new Scanner(currentExpression); // Use zero or more white space as delimiter, // which breaks the string into single character tokens currentExpressionScanner = currentExpressionScanner.useDelimiter("s*"); // Step 1: Scan the tokens in the string. while (currentExpressionScanner.hasNext()) { // Step 2: If you see an operand, push operand object onto the allTokensStack if (currentExpressionScanner.hasNextInt()) { // This force scanner to grab all of the digits // Otherwise, it will just get one char String dataString = currentExpressionScanner.findInLine("d+"); // more ... } else { // Get next token, only one char in string token String aToken = currentExpressionScanner.next(); //System.out.println("Other: " + aToken); char item = aToken.charAt(0); switch (item) { // Step 3: If you see "(", next token shoube an operator
  • 11. // Step 4: If you see an operator, push operator object onto the allTokensStack // Step 5: If you see ")" // steps in solveCurrentParenthesisOperation() : default: // error throw new LispExpressionException(item + " is not a legal expression operator"); } // end switch } // end else } // end while // Step 9: If you run out of tokens, the value on the top of allTokensStack is // is the result of the expression. // // return result return 0.0; // return the correct result } //==================================================================== = // DO NOT MODIFY ANY STATEMENTS BELOW //==================================================================== = // This static method is used by main() only private static void evaluateExprTest(String s, LispExpressionEvaluator expr, String expect) { Double result; System.out.println("Expression " + s); System.out.printf("Expected result : %s ", expect); expr.reset(s); try { result = expr.evaluate(); System.out.printf("Evaluated result : %.2f ", result); } catch (LispExpressionException e) { System.out.println("Evaluated result :"+e); }
  • 12. System.out.println("-----------------------------"); } // define few test cases, exception may happen public static void main (String args[]) { LispExpressionEvaluator expr= new LispExpressionEvaluator(); //expr.setDebug(); String test1 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))"; String test2 = "(+ (- 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)) (+ 0))"; String test3 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 1) (- 2 1 ))(* 1))"; String test4 = "(+ (/2)(+ 1))"; String test5 = "(+ (/2 3 0))"; String test6 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 3) (- 2 1 ))))"; String test7 = "(+ (*))"; String test8 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ ))"; evaluateExprTest(test1, expr, "17.50"); evaluateExprTest(test2, expr, "-378.12"); evaluateExprTest(test3, expr, "4.50"); evaluateExprTest(test4, expr, "1.5"); evaluateExprTest(test5, expr, "Infinity or LispExpressionException"); evaluateExprTest(test6, expr, "LispExpressionException"); evaluateExprTest(test7, expr, "LispExpressionException"); evaluateExprTest(test8, expr, "LispExpressionException"); } } You need to implement (15%) 85%) simpleLinkedStack. Java LISpExpressionEvaluator.java See proiect reauirements in LispExpressionEvaluator.java Upload single zip file containing above 2 files to ilearn Use PJ2 Test.iava to test correctness of vour program Compile programs (v ou are in directory containing Readme file): javac PJ2/*. java javac *. java C *.java Run programs (vou are in directory containing Readme file): // Run main() method tests in LispExpressionEvaluator java PJ2.SimpleLinkedStack java PJ2.LispExpressionEvaluator // Run main test program iava PJ2 Test Solution PROGRAM CODE: SimpleLinkedStack.java
  • 13. package PJ2; /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in SimpleLinkedStack class using the inner Node class. Main Reference : text book or class notes Do not change or add data fields Do not add new methods You may access Node object fields directly, i.e. data and next */ public class SimpleLinkedStack implements StackInterface { // Data fields private Node topNode; // references the first node in the chain private int count; // number of data in this stack public SimpleLinkedStack() { // initializing the data members this.topNode = null; this.count = 0; } // end default constructor public void push(T newData) { // checking if topnode is null if(topNode == null) { topNode = new Node(newData); topNode.next = null; } else { //if topnode is not null, store topnode in a new node and add the data to topnode and link next to the newnode
  • 14. Node node = new Node(newData); node.next = topNode; topNode = node; } } // end push public T peek() { // return the topnode's data if(topNode != null) return topNode.data; else return null; } // end peek public T pop() { // remove the topnode's data T deletedData = null; if(topNode != null) { deletedData = topNode.data; Node newnode = topNode.next; if(newnode != null) { topNode.data = newnode.data; topNode.next = newnode.next; } else { topNode = null; } } return deletedData; } // end pop public boolean empty() {
  • 15. // checking if the stack is empty if(topNode==null) return true; else return false; } // end empty public int size() { // add stataments int size = 0; Node newnode = topNode; while(newnode!=null) { size++; newnode = newnode.next; } return size; } // end isEmpty public void clear() { // clearing the whole stack topNode = null; } // end clear public String toString() { // add stataments // note: data class in stack must implement toString() method // return a list of data in Stack, separate them with ',' String value = "["; Node newnode = topNode; int counter = 0; while(counter s = new SimpleLinkedStack(); if (s.empty()) System.out.println("OK: stack is empty"); else System.out.println("Error: stack is not empty");
  • 16. s.push(10); s.push(30); s.push(50); System.out.println("Push 3 data: 10, 30, 50"); System.out.println("Print stack " + s); if (s.size() == 3) System.out.println("OK: stack size is 3"); else System.out.println("Error: stack size is " + s.size()); if (s.peek() == 50) System.out.println("OK: peek stack top is 50"); else System.out.println("Error: peek stack top is " + s.size()); if (!s.empty()) System.out.println("OK: stack is not empty"); else System.out.println("Error: stack is empty"); System.out.println("Pop 2 data: 50, 30"); s.pop(); System.out.println("Print stack " + s); int data=s.pop(); System.out.println("Print stack " + s); if (data == 30) System.out.println("OK: stack pop data is 30"); else System.out.println("Error: stack pop data is " + data); System.out.println("Clear stack"); s.clear(); System.out.println("Print stack " + s); } } // end Stack OUTPUT: ******************************************************* Sample Expected output: OK: stack is empty Push 3 data: 10, 30, 50
  • 17. Print stack [50,30,10,] OK: stack size is 3 OK: peek stack top is 50 OK: stack is not empty Pop 2 data: 50, 30 Print stack [30,10,] Print stack [10,] OK: stack pop data is 30 Clear stack Print stack [] ******************************************************* Your Test output: OK: stack is empty Push 3 data: 10, 30, 50 Print stack [50,30,10,] OK: stack size is 3 OK: peek stack top is 50 OK: stack is not empty Pop 2 data: 50, 30 Print stack [30,10,] Print stack [10,] OK: stack pop data is 30 Clear stack Print stack [] PROGRAM CODE: LispExpressionEvaluator.java /***************************************************************************** ******* * * CSC220 Programming Project#2 * * Specification: * * Taken from Project 7, Chapter 5, Page 178 * I have modified specification and requirements of this project *
  • 18. * Ref: http://www.gigamonkeys.com/book/ (see chap. 10) * * In the language Lisp, each of the four basic arithmetic operators appears * before an arbitrary number of operands, which are separated by spaces. * The resulting expression is enclosed in parentheses. The operators behave * as follows: * * (+ a b c ...) returns the sum of all the operands, and (+ a) returns a. * * (- a b c ...) returns a - b - c - ..., and (- a) returns -a. * * (* a b c ...) returns the product of all the operands, and (* a) returns a. * * (/ a b c ...) returns a / b / c / ..., and (/ a) returns 1/a. * * Note: + * - / must have at least one operand * * You can form larger arithmetic expressions by combining these basic * expressions using a fully parenthesized prefix notation. * For example, the following is a valid Lisp expression: * * (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1)) * * This expression is evaluated successively as follows: * * (+ (- 6) (* 2 3 4) (/ 3 1 -2) (+ 1)) * (+ -6 24 -1.5 1.0) * 17.5 * * Requirements: * * - Design and implement an algorithm that uses SimpleLinkedStack class to evaluate a * valid Lisp expression composed of the four basic operators and integer values. * - Valid tokens in an expression are '(',')','+','-','*','/',and positive integers (>=0) * - Display result as floting point number with at 2 decimal places * - Negative number is not a valid "input" operand, e.g. (+ -2 3)
  • 19. * However, you may create a negative number using parentheses, e.g. (+ (-2)3) * - There may be any number of blank spaces, >= 0, in between tokens * Thus, the following expressions are valid: * (+ (-6)3) * (/(+20 30)) * * - Must use StackInterface and SimpleLinkedStack in this project. (*** DO NOT USE Java API Stack class ***) * - Must throw LispExpressionException to indicate errors * - Must not add new or modify existing data fields * - Must implement methods in SimpleLinkedStack class. * - Must implement these methods in LispExpressionEvaluator class: * * public LispExpressionEvaluator() * public LispExpressionEvaluator(String inputExpression) * public void reset(String inputExpression) * public double evaluate() * private void solveCurrentParenthesisOperation() * * - You may add new private methods * ***************************************************************************** ********/ package PJ2; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class LispExpressionEvaluator { // Current input Lisp expression private String currentExpression; // Main expression stack, see algorithm in evaluate() private StackInterface allTokensStack; private StackInterface currentOperandsStack; // default constructor // set currentExpression to ""
  • 20. // create stack objects public LispExpressionEvaluator() { currentExpression = ""; allTokensStack = new SimpleLinkedStack(); currentOperandsStack = new SimpleLinkedStack(); } // constructor with an input expression // set currentExpression to inputExpression // create stack objects public LispExpressionEvaluator(String inputExpression) { currentExpression = inputExpression; allTokensStack = new SimpleLinkedStack(); currentOperandsStack = new SimpleLinkedStack(); } // set currentExpression to inputExpression // clear stack objects public void reset(String inputExpression) { currentExpression = inputExpression; allTokensStack.clear(); currentOperandsStack.clear(); } // This function evaluates current operator with its operands // See complete algorithm in evaluate() // // Main Steps: // Pop operands from allTokensStack and push them onto // currentOperandsStack until you find an operator // Apply the operator to the operands on currentOperandsStack // Push the result into allTokensStack
  • 21. // private void solveCurrentParenthesisOperation() { try{ String token = allTokensStack.pop().toString(); while(!token.equals("*") && !token.equals("/") && !token.equals("+") && !token.equals("-")) { currentOperandsStack.push(Double.valueOf(token)); token = allTokensStack.pop().toString(); } //System.out.println("operands: " + currentOperandsStack); //System.out.println("operator: " + token); Double result = currentOperandsStack.pop();; if(token.equals("*")) { while(!currentOperandsStack.empty()) { result = result * currentOperandsStack.pop(); } } else if(token.equals("+")) { while(!currentOperandsStack.empty()) { result = result + currentOperandsStack.pop(); } } else if(token.equals("-")) { if(currentOperandsStack.size() == 0) { result = -1 * result;
  • 22. } else { while(!currentOperandsStack.empty()) { result = result - currentOperandsStack.pop(); } } } else if(token.equals("/")) { if(currentOperandsStack.size() == 0) { result = 1/result; } else { while(!currentOperandsStack.empty()) { result = result / currentOperandsStack.pop(); } } } //System.out.println("my result: " + result); //rounding to two decimal value allTokensStack.push(result); } catch(Exception e) { throw new LispExpressionException("LispExpressionException"); } } /**
  • 23. * This funtion evaluates current Lisp expression in currentExpression * It return result of the expression * * The algorithm: * * Step 1 Scan the tokens in the string. * Step 2 If you see an operand, push operand object onto the allTokensStack * Step 3 If you see "(", next token should be an operator * Step 4 If you see an operator, push operator object onto the allTokensStack * Step 5 If you see ")" // steps in solveCurrentParenthesisOperation() : * Step 6 Pop operands and push them onto currentOperandsStack * until you find an operator * Step 7 Apply the operator to the operands on currentOperandsStack * Step 8 Push the result into allTokensStack * Step 9 If you run out of tokens, the value on the top of allTokensStack is * is the result of the expression. */ public double evaluate() throws LispExpressionException { // only outline is given... // you need to add statements/local variables // you may delete or modify any statements in this method double result = 0; // use scanner to tokenize currentExpression Scanner currentExpressionScanner = new Scanner(currentExpression); // Use zero or more white space as delimiter, // which breaks the string into single character tokens currentExpressionScanner = currentExpressionScanner.useDelimiter("s*"); // Step 1: Scan the tokens in the string. while (currentExpressionScanner.hasNext()) { // Step 2: If you see an operand, push operand object onto the allTokensStack if (currentExpressionScanner.hasNextInt()) {
  • 24. // This force scanner to grab all of the digits // Otherwise, it will just get one char String dataString = currentExpressionScanner.findInLine("d+"); //System.out.println(dataString); allTokensStack.push(Double.valueOf(dataString)); // more ... } else { // Get next token, only one char in string token String aToken = currentExpressionScanner.next(); //System.out.println("Other: " + aToken); char item = aToken.charAt(0); switch (item) { // Step 3: If you see "(", next token shoube an operator // Step 4: If you see an operator, push operator object onto the allTokensStack // Step 5: If you see ")" // steps in solveCurrentParenthesisOperation() : case '(': break; case ')' : solveCurrentParenthesisOperation(); break; case '*' : case '+' : case '-' : case '/' : allTokensStack.push(item); break; default: // error throw new LispExpressionException(item + " is not a legal expression operator"); } // end switch } // end else } // end while // Step 9: If you run out of tokens, the value on the top of allTokensStack is // is the result of the expression. //
  • 25. // return result try { result = (Double) allTokensStack.peek(); } catch(Exception e) { throw new LispExpressionException("LispExpressionException"); } return result; } //==================================================================== = // DO NOT MODIFY ANY STATEMENTS BELOW //==================================================================== = // This static method is used by main() only private static void evaluateExprTest(String s, LispExpressionEvaluator expr, String expect) { Double result; System.out.println("Expression " + s); System.out.printf("Expected result : %s ", expect); expr.reset(s); try { result = expr.evaluate(); System.out.printf("Evaluated result : %.2f ", result); } catch (LispExpressionException e) { System.out.println("Evaluated result :"+e); } System.out.println("-----------------------------"); } // define few test cases, exception may happen public static void main (String args[]) {
  • 26. LispExpressionEvaluator expr= new LispExpressionEvaluator(); //expr.setDebug(); String test1 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1))"; String test2 = "(+ (- 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)) (+ 0))"; String test3 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 1) (- 2 1 ))(* 1))"; String test4 = "(+ (/2)(+ 1))"; String test5 = "(+ (/2 3 0))"; String test6 = "(+ (/ 2) (* 2) (/ (+ 1) (+ 3) (- 2 1 ))))"; String test7 = "(+ (*))"; String test8 = "(+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ ))"; evaluateExprTest(test1, expr, "17.50"); evaluateExprTest(test2, expr, "-378.12"); evaluateExprTest(test3, expr, "4.50"); evaluateExprTest(test4, expr, "1.5"); evaluateExprTest(test5, expr, "Infinity or LispExpressionException"); evaluateExprTest(test6, expr, "LispExpressionException"); evaluateExprTest(test7, expr, "LispExpressionException"); evaluateExprTest(test8, expr, "LispExpressionException"); } } OUTPUT: Expression (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ 1)) Expected result : 17.50 Evaluated result : 17.50 ----------------------------- Expression (+ (- 632) (* 21 3 4) (/ (+ 32) (* 1) (- 21 3 1)) (+ 0)) Expected result : -378.12 Evaluated result : -378.12 ----------------------------- Expression (+ (/ 2) (* 2) (/ (+ 1) (+ 1) (- 2 1 ))(* 1)) Expected result : 4.50 Evaluated result : 4.50 ----------------------------- Expression (+ (/2)(+ 1)) Expected result : 1.5 Evaluated result : 1.50
  • 27. ----------------------------- Expression (+ (/2 3 0)) Expected result : Infinity or LispExpressionException Evaluated result : Infinity ----------------------------- Expression (+ (/ 2) (* 2) (/ (+ 1) (+ 3) (- 2 1 )))) Expected result : LispExpressionException Evaluated result :PJ2.LispExpressionException: LispExpressionException ----------------------------- Expression (+ (*)) Expected result : LispExpressionException Evaluated result :PJ2.LispExpressionException: LispExpressionException ----------------------------- Expression (+ (- 6) (* 2 3 4) (/ (+ 3) (* 1) (- 2 3 1)) (+ )) Expected result : LispExpressionException Evaluated result :PJ2.LispExpressionException: LispExpressionException -----------------------------