stackhmk.zip ( 1.96k )
Number of downloads: 38Ok,
The purpose of this assignment is to make a postfix boolean expression evaluator program using the ! && and || operators.
These are the postfixes for the assignment:
true false && <-----WORKS
postfix for: true && false = false
true false ! && <-----DOESN'T
postfix for: true && !false = true
true true ! false || ! && true false && || <-----DOESN'T
postfix for: true && !(!true || false) || (true && false) = true
the first one works! However, the following two do not, and throw the following error: exception in thread "main" EmptyStackException at line 44.
One of the other requirements for this assignment is to apply the ! operator only to the most recent pushed operand....
I do not know how to accomplish this.... and am open to suggestions.
any help you can provide will be greatly appreciated.
Cobrec
CODE
//clarified version of PostFixEvaluator of section 3.8
//input a string of a valid PeckPostfix expression of integers, evaluate it.
import java.util.*;
import javax.swing.*;
public class PeckPostfix {
public static void main(String[] args) {
String expression;
String token;
String operator;
StringTokenizer tokens;
Boolean result=true;
Boolean operand1=true;
Boolean operand2=false;
//create empty stack of pending Boolean operands
Stack operandStack = new Stack();
expression = JOptionPane.showInputDialog( "Enter Postfix expression" );
tokens = new StringTokenizer(expression);
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (!isOperator(token)) //operand
//extract boolean from String token, create Boolean object, push onto stack
operandStack.push(new Boolean(token));
// printStack(operandStack); //display stack at each step. Debugging
else { //token is an operator
//pop two ints off stack.
//convert popped Object to Boolean, extract boolean
operand2 = ((Boolean)operandStack.pop());
operand1 = ((Boolean)operandStack.pop()); //"first" one
if (token.equals("!"))
result = operand1 != operand2;
else if (token.equals("&&"))
result = operand1 && operand2;
else if (token.equals("||"))
result = operand1 || operand2;
operandStack.push(new Boolean(result));
}
}
//only object in stack is the answer
result = ((Boolean)operandStack.pop());
JOptionPane.showMessageDialog(null,expression+" = "+result);
System.exit(0);
}
static boolean isOperator(String t) {
if (t.equals("!") || t.equals("&&") || t.equals("||"))
return true;
else
return false;
}
static void printStack( Stack s) {
System.out.print("Stack is: ");
//don't normally iterate over a stack. here for illustration purposes.
Iterator items = s.iterator();
while (items.hasNext())
System.out.print(items.next()+" ");
System.out.println();
}
}
/*
true false &&
postfix for: true && false = false
true false ! &&
postfix for: true && !false = true
true true ! false || ! && true false && ||
postfix for: true && !(!true || false) || (true && false) = true
*/
This post has been edited by cobrec: 1 Jul, 2007 - 07:11 PM