Expression tree won't work properly with numbers bigger than 9 - java

I am finishing up an expression tree program that takes in a postfix and gives the answer and the orginal equation back in infix form. I started working on about 6 months ago and had an issue I couldn't figure out. It works fine if the numbers are smaller than 9. For instance, 2 5 * 4 - prints out The infix: (2*5-4) 6.0 works fine. Something like 10 2 * prints out 20.0 but prints out The infix: (0*2) which isn't right. The big problem is that if a number is bigger than 9 it doesn't read that number in properly which messes up the conversion to infix. I am not sure how to fix this problem exactly. Below is my class and tester class:
import java.util.NoSuchElementException;
import java.util.Stack;
public class ExpressionTree
{
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and its used to construct the expression tree.
*/
public ExpressionTree(String postfix)
{
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode
{
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
/**
* Checks to see if it is an Operator
*/
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree()
{
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++)
{
char ch = postfix.charAt(i);
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else if (!Character.isWhitespace(ch))
{
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the infix expression
*
* #return the string of infix.
*/
public String infix()
{
if (root == null)
{
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix)
{
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
public Double evaluate(String postfix)
{
Stack<Double> s = new Stack<Double>();
char[] chars = postfix.toCharArray();
int N = chars.length;
for(int i = 0; i < N; i++)
{
char ch = chars[i];
if(isOperator(ch))
{
switch(ch)
{
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
}
else if(Character.isDigit(ch))
{
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
return s.pop();
}
}
And the tester:
import java.util.Scanner;
public class ExpressionTester
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String line = null;
while(true)
{
System.out.println("");
String pf = sc.nextLine();
if (pf.isEmpty())
{
break;
}
ExpressionTree eT = new ExpressionTree(pf);
eT.createExpressionTree();
System.out.println("The infix: " + "(" + eT.infix() + ")" );
System.out.println(eT.evaluate(pf));
}
}
}

Related

How to do different traversals of an expression tree?

I'm trying to figure out how to do the different traversals through an expression tree. For example, if I type in " - + 10 * 2 8 3 ", I want it to print out the prefix, postfix, and infix versions of that expression.
I also need to calculate the result of the expression through a postorder traversal, which should be the evaluate function.
However, when I run my program, I only get the first character of each expression. Is my understanding of how these traversals work wrong?
EDIT: Following suggestions, I saved the result of the buildtree and also changed sc.next to sc.nextLine.
Also, every method should be recursive.
Given "- + 10 * 2 8 3", the expected answer would be:
prefix expression:
- + 10 * 2 8 3
postfix expression:
10 2 8 * + 3 -
infix expression:
( ( 10 + ( 2 * 8 ) ) - 3 )
Result = 23
I understand I haven't implemented anything with parentheses for the infix expression, but that's okay for now.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a prefix expression: ");
Node root = buildTree(sc);
System.out.println("prefix expression: ");
infix(root);
System.out.println("postfix expression: ");
postfix(root);
System.out.println("infix expression: ");
infix(root);
System.out.print("Result = ");
evaluate(root);
}
static Node buildTree(Scanner sc) {
Node n = new Node(null);
int i = 0;
String prefixExpression = sc.nextLine();
String[] temp = prefixExpression.split(" ");
if(n.isLeaf()) {
n.value = temp[i];
n.left = null;
n.right = null;
i++;
}
return n;
}
static void infix(Node node) {
if(node.isLeaf()){
System.out.println(node.value);
}
else {
infix(node.left);
System.out.println(node.value + " ");
infix(node.right);
}
}
void prefix(Node node) {
if(node.isLeaf()){
System.out.println(node.value);
}
else {
switch(node.value) {
case "+":
System.out.print("+");
break;
case "-":
System.out.print("-");
break;
case "*":
System.out.print("*");
break;
case "/":
System.out.print("/");
break;
}
}
prefix(node.left);
System.out.print(" ");
prefix(node.right);
}
static void postfix(Node node) {
if(node.isLeaf()){
System.out.println(node.value);
}
else {
postfix(node.left);
postfix(node.right);
switch (node.value) {
case "+":
System.out.print("+");
break;
case "-":
System.out.print("-");
break;
case "*":
System.out.print("*");
break;
case "/":
System.out.print("/");
break;
}
}
}
public static int evaluate(Node node) {
if(node.isLeaf()) {
return Integer.parseInt(node.value);
}
else {
int leftHandSide = evaluate(node.getLeft());
int rightHandSide = evaluate(node.getRight());
String operator = node.getValue();
if("+".equals(operator)) {
return leftHandSide + rightHandSide;
}
else if("-".equals(operator)) {
return leftHandSide - rightHandSide;
}
else if("*".equals(operator)) {
return leftHandSide * rightHandSide;
}
else if("/".equals(operator)) {
return leftHandSide / rightHandSide;
}
else {
System.out.println("Unexpected problem. Error.");
}
return 0;
}
}
}
Here is Node.java, There's getters and setters too.
public class Node<E> {
String value;
Node<E> left;
Node<E> right;
Node(String value){
left = null;
right = null;
this.value = value;
}
Node(String value, Node<E> left, Node<E> right) {
this.value = value;
this.left = left;
this.right = right;
}
boolean isLeaf() {
return (left == null && right == null);
}
EDIT:
Since your question says "How to do different traversals of an expression tree?, The problem I can see in your code is building the tree ( i.e. buildTree() method).
In order to correct this, I have used buildExpressionTree(array) method to convert your prefix input to an expression tree using Stack data structure.
Construction of Expression Tree:
For constructing expression tree I have use a stack. Since in your case input is in prefix form so Loop in reverse through input expression and do following for every character.
If character is operand push that into stack
If character is operator pop two values from stack make them its
child and push current node again.
At the end only element of stack will be root of expression tree.
Also while printing different traversals, you do not need all those if conditions to check for different operators.You can simply do the traversal as shown in my code below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a prefix expression: ");
String prefixExpression = sc.nextLine();
String[] temp = prefixExpression.split(" ");
Node n = null;
n = buildExpressionTree(temp);
System.out.println("prefix expression: ");
prefix(n);
System.out.println();
System.out.println("postfix expression: ");
postfix(n);
System.out.println();
System.out.println("infix expression: ");
infix(n);
System.out.println();
int result = evaluate(n);
System.out.print("Result = "+ result);
}
static Node buildExpressionTree(String[] input) {
Stack<Node> st = new Stack();
Node t, t1, t2;
// Traverse through every character of
// input expression
for (int i = (input.length-1); i >= 0; i--) {
// If operand, simply push into stack
if (isNumber(input[i])) {
t = new Node(input[i]);
st.push(t);
} else // operator
{
t = new Node(input[i]);
// Pop two top nodes
// Store top
t1 = st.pop(); // Remove top
t2 = st.pop();
// make them children
t.left = t1;
t.right = t2;
st.push(t);
}
}
t = st.peek();
st.pop();
return t;
}
static boolean isNumber(String s) {
boolean numeric = true;
try {
Integer num = Integer.parseInt(s);
} catch (NumberFormatException e) {
numeric = false;
}
return numeric;
}
static void infix(Node node) {
if( null == node) {
return;
}
infix(node.left);
System.out.print(node.value + " ");
infix(node.right);
}
static void prefix(Node node) {
if( null == node) {
return;
}
System.out.print(node.value+ " ");
prefix(node.left);
prefix(node.right);
}
static void postfix(Node node) {
if( null == node) {
return;
}
postfix(node.left);
postfix(node.right);
System.out.print(node.value+ " ");
}
public static int evaluate(Node node) {
if(node.isLeaf()) {
return Integer.parseInt(node.value);
}
else {
int leftHandSide = evaluate(node.left);
int rightHandSide = evaluate(node.right);
String operator = node.value;
if("+".equals(operator)) {
return leftHandSide + rightHandSide;
}
else if("-".equals(operator)) {
return leftHandSide - rightHandSide;
}
else if("*".equals(operator)) {
return leftHandSide * rightHandSide;
}
else if("/".equals(operator)) {
return leftHandSide / rightHandSide;
}
else {
System.out.println("Unexpected problem. Error.");
}
return 0;
}
}
OUTPUT:
Enter a prefix expression:
- + 10 * 2 8 3
prefix expression:
- + 10 * 2 8 3
postfix expression:
10 2 8 * + 3 -
infix expression:
10 + 2 * 8 - 3
Result = 23

File reading error with postfix calculator

I made a postfix calculator and I'm pretty sure it works however it as a reading error. The calculator is designed to read numbers in postfix notation from a line in a file and calc them. However it doesn't recognize lines, for example if I have two lines it will combine the two expressions. I have trouble with file reading so any help would be appreciated. Sorry for any format problem this is my first post. So here is my code so my issue is better understood.
import java.io.*;
import java.util.*;
import java.nio.charset.Charset;
public class PostfixCalculator {
private static final String ADD = "+";
private static final String SUB = "-";
private static final String MUL = "*";
private static final String DIV = "/";
private static final String EXP = "^";
private static final String NEG = "_"; //unary negation
private static final String SQRT = "#";
public void calculateFile(String fileName) throws IOException {
BufferedReader br = null;
StringBuilder sb = null;
try {
FileReader fileReader = new FileReader(fileName);
br = new BufferedReader(fileReader);
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String input = sb.toString();
System.out.println(input + " = " + calculate(input));
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
}
private double calculate(String input) {
SinglyLinkedListStack<Double> stack = new SinglyLinkedListStack<Double>();
String[] inputs = input.split(" ");
return handleCalculation(stack, inputs);
}
private static double handleCalculation(SinglyLinkedListStack<Double> stack, String[] el) {
double operand1, operand2;
for(int i = 0; i < el.length; i++) {
if( el[i].equals(ADD) || el[i].equals(SUB) || el[i].equals(MUL) || el[i].equals(DIV)||el[i].equals(EXP)||el[i].equals(NEG)||el[i].equals(SQRT)) {
operand2 = stack.pop();
operand1 = stack.pop();
switch(el[i]) {
case ADD: {
double local = operand1 + operand2;
stack.push(local);
break;
}
case SUB: {
double local = operand1 - operand2;
stack.push(local);
break;
}
case MUL: {
double local = operand1 * operand2;
stack.push(local);
break;
}
case DIV: {
double local = operand1 / operand2;
stack.push(local);
break;
}
case EXP: {
double local = Math.pow(operand1, operand2);
stack.push(local);
break;
}
case NEG: {
double local = -(operand1);
stack.push(local);
break;
}
case SQRT:{
double local = Math.pow(operand1, .5);
stack.push(local);
break;
}
}
} else {
stack.push(Double.parseDouble(el[i]));
}
}
return (double)stack.pop();
}
}
This is my linked list
public class SinglyLinkedListStack<T> {
private int size;
private Node<T> head;
public SinglyLinkedListStack() {
head = null;
size = 0;
}
public void push(double local) {
if(head == null) {
head = new Node(local);
} else {
Node<T> newNode = new Node(local);
newNode.next = head;
head = newNode;
}
size++;
}
public T pop() {
if(head == null)
return null;
else {
T topData = head.data;
head = head.next;
size--;
return topData;
}
}
public T top() {
if(head != null)
return head.data;
else
return null;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
private class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
}
This is my demo
import java.io.IOException;
public class PostFixCalculatorDemo {
public static void main(String[] args) throws IOException {
PostfixCalculator calc = new PostfixCalculator();
calc.calculateFile("in.dat");
}
}
The text file contains
2 3 ^ 35 5 / -
1 2 + 3 * # 4 - 5 6 - + _
my output is 2 3 ^ 35 5 / -1 2 + 3 * # 4 - 5 6 - + _ = -8.0
as it is seen it is combining the two lines. I want it to read the two lines separately and calculate 2 3 ^ 35 5 / - and 1 2 + 3 * # 4 - 5 6 - + _ without putting it together. I know it does this because I programmed the calculateFile class wrong but I am not sure how to fix this without breaking my program.
while (line != null) {
sb.append(line);
line = br.readLine();
}
Basically you are reading every line and appending it to a single Stringbuffer which will result in concatenation of every line from your file. This buffer wont contain newline character or any other sign where your lines end.
From the documentation:
readline:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached Throws:
I advice adding the lines to an ArrayList if you are planning to read everything at once.

Convert a Postfix expression to infix and calculate the postfix and give the answer

I have been working on this program to take in a postfix expression, calculate and print out its answer, and also convert it to infix expression. I have gotten the calculation part of it to work. For instance, if I enter 2 2 +(accounting for the spacing) it gives me 4. However, for the infix part of it it prints out 2+. I then tried it just doing it without any spacing. I put in 22+. The postfix did not work, but the infix printed out properly. So I am not sure how to fix this part of it. Here is my code.
import java.util.NoSuchElementException;
import java.util.Stack;
public class ExpressionTree
{
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and later its used to construct the expression tree.
* The posfix expression, if invalid, leads to invalid results
*
* #param postfix the postfix expression.
*/
public ExpressionTree(String postfix)
{
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode
{
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree()
{
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++)
{
char ch = postfix.charAt(i);
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
} else
{
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the infix expression
*
* #return the string of infix.
*/
public String infix()
{
if (root == null)
{
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix) {
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
public Double evaluate(String postfix)
{
Stack<Double> s = new Stack<Double>();
char[] chars = postfix.toCharArray();
int N = chars.length;
for(int i = 0; i < N; i++)
{
char ch = chars[i];
if(isOperator(ch))
{
switch(ch)
{
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
}
else if(Character.isDigit(ch))
{
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
return s.pop();
}
}
And here is my tester:
import java.util.Scanner;
public class ExpressionTester
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("");
String pf = sc.nextLine();
ExpressionTree eT = new ExpressionTree(pf);
eT.createExpressionTree();
System.out.println("The infix: " + eT.infix() );
System.out.println(eT.evaluate(pf));
}
}
}
Any help would be greatly appreciated, as I really do not know how to fix this issue, and I am so close to finishing it.
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else
{
nodes.add(new TreeNode(null, ch, null));
}
You're putting whitespace nodes into the tree. Try this:
if (isOperator(ch))
{
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
}
else if (!Character.isWhitespace(ch))
{
nodes.add(new TreeNode(null, ch, null));
}

Code help, can't get binary tree

So my goal is turn some sort of expression into a postfix expression (check), and then convert that expression into a binary tree. Here is my main class
public class ConvertIntoTree
{
public static void main(String[] args)
{
// Create a new InfixToPostfix expression from input
InfixtoPostfix mystack = new InfixtoPostfix(15);
System.out.println("Type in an expression like (1+2)*(3+4)/(12-5) //No spaces ");
Scanner scan = new Scanner(System.in);
String str = scan.next();
System.out.println("The Expression you have typed in infix form :\n"+str);
System.out.println("The Expression in Postfix is :\n"+mystack.InToPost(str));
ExpressionTree expressionTree = new ExpressionTree(str);
expressionTree.createExpressionTree();
//expressionTree.prefix();
System.out.println("The Expression I want");
expressionTree.infix();
}
}
and here is my expression tree class
class ExpressionTree {
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and later its used to construct the expression tree.
* The posfix expression, if invalid, leads to invalid results
*
* #param postfix the postfix expression.
*/
public ExpressionTree(String postfix) {
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode {
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree() {
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix.charAt(i);
if (isOperator(ch)) {
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
} else {
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the prefix notation
*
* #return the prefix notation
*/
public String prefix() {
if (root == null) {
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder prefix = new StringBuilder();
preOrder(root, prefix);
return prefix.toString();
}
private void preOrder(TreeNode node, StringBuilder prefix) {
if (node != null) {
prefix.append(node.ch);
preOrder(node.left, prefix);
preOrder(node.right, prefix);
}
}
/**
* Returns the infix expression
*
* #return the string of infix.
*/
public String infix() {
if (root == null) {
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix) {
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
}
After I run expressionTree.infix();, nothing. Obviously I'm doing something wrong. Any ideas or help, thanks.
After a little tinkering, the main issue was using expressionTree2.infix()
instead of System.out.println(expressionTree2.infix());

NullPointerException infix to postfix java using stack [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Currently I am working on a project using an ArrayStack to change an infix to postfix and evaluating the postfix evaluation. For the first operator that appears when the program reads it, it sends back
java.lang.NullPointerException
at InfixToPostfix.convertString(InfixToPostfix.java:27)
at Postfix.main(Postfix.java:20)
I debugged the program and I know it will have to deal with my push method in ArrayStack. I just don't know how to get rid of NullPointerException.
Here is my ArrayStack class.
import java.util.*;
public class ArrayStack<T> implements StackADT<T>{
private int top = 0;
private static final int DEFAULT_CAPACITY = 70;
private T[] stack;
#SuppressWarnings("unchecked")
public ArrayStack()
{
top = 0;
stack = (T[])(new Object[DEFAULT_CAPACITY]);
}
#SuppressWarnings("unchecked")
public ArrayStack (int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
public boolean isEmpty()
{
if(top==0)
return true;
else
return false;
}
public T pop() throws StackIsEmptyException
{
T retVal;
if(isEmpty())
throw new StackIsEmptyException("Stack is Empty");
else{
top--;
retVal = stack[top];
}
return retVal;
}
**public void push (T element)
{
if (size() == stack.length)
expandCapacity();
top++;
element = stack[top];
}**
public T peek() throws StackIsEmptyException
{
if (isEmpty())
throw new StackIsEmptyException("Stack is Empty");
return stack[top-1];
}
#SuppressWarnings("unchecked")
private void expandCapacity()
{
T[] larger = (T[])(new Object[stack.length*2]);
for (int index=0; index < stack.length; index++)
larger[index] = stack[index];
stack = larger;
}
#Override
public String toString() {
String result = "";
for (int scan=0; scan < top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
#Override
public int size() {
return top;
}
}
InfixToPostfix classe
public class InfixToPostfix {
private ArrayStack<Character> stack;
private String infix;
private String postfix= "";
public InfixToPostfix(String in, ArrayStack<Character> stack) {
infix = in;
this.stack = stack;
}
#SuppressWarnings("unused")
public String convertString (){
for (int i = 0; i< infix.length(); i++){
try {
char curChar = infix.charAt(i);
if(!isOperator(curChar)){
postfix = postfix + curChar;
if (i == (infix.length()-1)){
while(!stack.isEmpty()){
postfix += stack.pop();
}
}
}**else if(stack.isEmpty()&& isOperator(curChar)){
stack.push(curChar);**
}
else if(charPrec(curChar) == 4){
while (!stack.isEmpty() && stack.size() != '('){
postfix += stack.pop();
}
stack.pop();
}else if(!(stack.isEmpty())&&(precident(curChar,stack.peek()))){
stack.push(curChar);
if(charPrec(stack.peek())==3)
stack.push(curChar);
while (!(stack.isEmpty())&&(!precident(curChar,stack.peek()))){
postfix += stack.pop();
}
stack.push(curChar);
}
}
catch (StackIsEmptyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return postfix;
}
/**
* Evaluates the specified postfix expression. If an operand is
* encountered, it is pushed onto the stack. If an operator is
* encountered, two operands are popped, the operation is
* evaluated, and the result is pushed onto the stack.
* #param expr String representation of a postfix expression
* #return int value of the given expression
*/
public int evaluate (String expr)
{
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr);
/* while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
if (isOperator(token))
{
op2 = (stack.pop()).charValue();
op1 = (stack.pop()).charValue();
result = evalSingleOp (token.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push (new Integer(Integer.parseInt(token)));
} */
return result;
}
/**
* Determines if the specified token is an operator.
* #param token String representing a single token
* #return boolean true if token is operator
*/
private boolean isOperator (String token)
{
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/") );
}
/**
* Performs integer evaluation on a single expression consisting of
* the specified operator and operands.
* #param operation operation to be performed
* #param op1 the first operand
* #param op2 the second operand
* #return int value of the expression
*/
private int evalSingleOp (char operation, int op1, int op2)
{
int result = 0;
switch (operation)
{
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
}
return result;
}
private boolean isOperator(char ch) {
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
private boolean precident(char one, char two) {
if(charPrec(one) >= charPrec(two));
return true;
}
private int charPrec(char ch) {
switch(ch) {
case '-':
return 1;
case '+':
return 1;
case '*':
return 2;
case '/':
return 2;
case '(':
return 3;
case ')':
return 4;
}
return 0; }
}
There are a few problems in your code... heres the ones I see:
when did a size() method ever return a char value? size() is a really bad method name.
The whole ArrayStack<T> implements StackADT<T> class should probably be CharacterStack implments StackADT<Character> which would simplify a lot of things
This line which I believe is on line 27 (where your nullpointer is), has: stack.size() != '(' but that makes little or no sense..... although it won't throw a null-pointer.
you do not indicate which line has the problem - mark it in the actual code so we can see it, and not have to count the lines ourselves.
The code method and variable names make reading it very difficult. Fix up your naming conventions, edit, and retry.
My guess is that if you todied up the code you will find the problem yourself.

Categories