3

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; }
  }
Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122
Edwin Lobo
  • 33
  • 6

1 Answers1

0

There are a few problems in your code... heres the ones I see:

  1. when did a size() method ever return a char value? size() is a really bad method name.
  2. The whole ArrayStack<T> implements StackADT<T> class should probably be CharacterStack implments StackADT<Character> which would simplify a lot of things
  3. 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.
  4. 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.

rolfl
  • 16,851
  • 6
  • 38
  • 72
  • 1
    Well I named it array stack since its a stack that uses the array instead of a linked list. But i just edited it since the size method didn't make sense and had it how I originally had it. The null pointer is for the push method under the first elseif in the convertString method. – Edwin Lobo Sep 21 '13 at 16:43