0

I'm a Java noobie so I'm still not familiar with the tools this language has. What I'm writing is an expression evaluation program, whose only operations are * and +. For input : 2+2*2*2*2*2*2+2*2 I should get an output of 70 but instead, my main throws a java.lang.NullPointerException where I call the function and where I try to push it on the stack. I've tried using Charachter.valueOf() but the outcome is the same. My questions are:

  • How to convert a primitive type char to a Character?

  • Why is new Character deprecated?

Here is my stack implementation: https://pastebin.com/QmA7JbJ2

public class MainClass {          //ExpressionEvaluator MainClass

     public static int evaluateExpression(String expression){
         int evaluation = 0, a = 0, b = 0, tmp = 0;
         char ch1, ch2, op;
         LinkedStack<Character> operand = null;
         LinkedStack<Character> operator = null;
         for(int k = 0; k<expression.length(); k++){
             if(Character.isDigit(expression.charAt(k))){
                 op = expression.charAt(k);
                 operand.push(new Character(op)); // <----- then error here
            }                                           // won't let me push it on the stack
            else{
                operator.push(expression.charAt(k));
            }
        }
        if(operator.peek() == '*'){
            evaluation = 1;
        }
        while(!operand.isEmpty() && !operator.isEmpty()){
            a = operand.pop();          
            ch1 = operator.pop();       
            if(ch1 == '*'){             
                evaluation *= a*operand.pop();
            }
            else{                       
                tmp = a;                
                a = operand.pop();      
                ch2 = operator.pop();   
                if (ch2 == '*'){
                    evaluation *= a*operand.pop();
                }
                else{
                    evaluation += a+tmp;
                }
            }
        }
        return evaluation;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
        System.out.println(evaluateExpression(input.readLine()));//  <--------   first error here
    }

}
ptushev
  • 156
  • 3
  • 13

0 Answers0