 # Java Programming - Lisp Evaluator

## Question

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 operations behave as follows.
• (+ a b c …) returns the sum of all operands, and (+) returns 0.
• (- a b c …) returns a-b-c- … and (- a) returns –a. The minus operator must have at least one operand.
• (* a b c …) returns the product of all the operands, and (*) returns 1.
• (/ a b c …) returns a/b/c/ … and (/ a) returns 1 / a. The divide operator 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) (*) (- 2 3 1)))
The expression is successively evaluated as follows:
(+ -6 24 (/ 3 1 -2))
(+ -6 24 -1.5)
16.5

Design and implement an algorithm that uses a stack to evaluate a legal Lisp expression composed of the four basic operators and integer values. Write a main program (LispEvaluator.java) that reads such an expression and demonstrates your algorithm.

## Solution Preview

This material may consist of step-by-step explanations on how to solve a problem or examples of proper writing, including the use of citations, references, bibliographies, and formatting. This material is made available for the sole purpose of studying and learning - misuse is strictly forbidden.

import java.util.Stack;

/*
* Lisp Class
* - performs evaluation of Lisp expression
*/
public class Lisp {

// String to hold original expression
private String expression;
// Stack to hold operators
private Stack<String> operators;
// Stack to hold operands
private Stack<String> operands;

// Constructor
public Lisp(String expression) {
this.expression = expression;
this.operators = new Stack<String>();
this.operands = new Stack<String>();
}

// Main method which evaluates expression
public void evaluate() {
// Convert expression to tokens
String[] tokens = expression.replaceAll("\\(","( ").replaceAll("\\)"," )").split("\\s+");
for (String token: tokens) {
// Close parenthesis - do operation
if (token.charAt(0) == ')') {
operation();
// Push operator into operator Stack
} else if (token.charAt(0) == '+' || token.charAt(0) == '-' || token.charAt(0) == '*' || token.charAt(0) == '/') {
operators.push(token);
// Push operand into operand Stack
} else {
operands.push...
\$40.50 for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

### Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.