java program for evaluating postfix expression results in numberformat exception in one of the methods leetcode #150 for stack.Suggest changes please

smit
class Solution {
     public boolean isoperand(String ch)
        {
            return(Integer.parseInt(ch)>=0 && Integer.parseInt(ch)<=9) ;
             
        }
     public int operate(String ch,int a,int b)
        {
            switch(ch){
                case "*":return a*b;
                case "/":return a/b;
                case "+":return a+b;
                case "-":return a-b;
                
            }
         return 0;
        }
    public int evalRPN(String[] tokens) {
    Stack<String> st=new Stack<>();
       
       
        int l=tokens.length;
        for(int i=0;i<l;i++)
        {
            if(isoperand(tokens[i]))
                st.push(tokens[i]);
            else{
                int b=Integer.parseInt(st.pop());
                int a=Integer.parseInt(st.pop());
                int result=operate(tokens[i],a,b);
                st.push(Integer.toString(result));
            }
            
            
        }
        
        
            int temp=Integer.parseInt(st.pop());
        
        return temp;
        
    }
}

this is my program to implement evaluation of postfix expression in stack. Can anyone help me? i get a numberformat exception when the method isoperand is executed. i am fairly new to java.

GURU Shreyansh

The issue with your code is that isoperand returns true only if the number lies between 0 and 9, which is not the case. We have numbers that are greater than 9 as well. Hence it results in RuntimeError.
So, it's always better to check if the current token is an operator, if not then it must be an operand.
I've used a set to efficiently check if the current token is an operator or not by adding all operators: +, -, *, / to the set.
Here is an improved version of your code:

class Solution
{
    public int operate(String ch, int a, int b)
    {
        switch (ch)
        {
            case "*": return a*b;
            case "/": return a/b;
            case "+": return a+b;
            case "-": return a-b; 
        }
        return 0;
    }
    public int evalRPN(String[] tokens)
    {
        Set<String> operators = new HashSet<>();
        operators.add("*"); operators.add("/");
        operators.add("+"); operators.add("-");
        
        Stack<String> stack = new Stack<>();
        int len = tokens.length;
        for (int i=0; i<len; i++)
        {
            if (operators.contains(tokens[i]))
            {
                int b = Integer.parseInt(stack.pop());
                int a = Integer.parseInt(stack.pop());
                int result = operate(tokens[i], a, b);
                stack.push(Integer.toString(result));
            }
            else
                stack.push(tokens[i]);
        }
        return Integer.parseInt(stack.pop());
    }
}

Runtime: 4 ms, faster than 88.95% of Java submissions

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Ternary operator in Java only evaluating one expression since Java 7 - was that different in Java 1.6 and lower?

Eclipse does not suggest methods in Lambda expression

Please suggest a Java Framework to make the CRUD easy

Please suggest some tutorial for learning pointcut expression

Please, suggest custom findBy or query

Java Evaluating a mathematical expression using prefix notation

Segmentation fault occuring in evaluation of postfix expression using stack

Evaluating a math expression with variables. (java 8)

a Java methods operand stack

Calling Azure Function 150 times by HTTP results in exception

JAVA Evaluating postfix expressions -- unable to throw empty or invalid expressions

Exception evaluating SpringEL expression, spring guru course

Please suggest how to debug

Exception while evaluating service stack text for iOS

Freemarker - Evaluating an expression one after another

erlang: exception error when evaluating an arithmetic expression

Please suggest correct regular expression for below situation

Calling Java Methods from JNI results in program crash

Evaluating PostFix Function

java program with methods and boolean

what is the importance of push(po[i]-'0') in the following snippet for evaluating postfix expression

Optimizing stack size for evaluating RPN expression

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "ServiceAmc.id" (results:30)

Stack Overflow Exception in Java

JOIN from tables evaluating results from one of them

how to resolve this : Exception evaluating SpringEL expression: "#authorization.expression('isAuthenticated()')"?

Thymeleaf: "Exception evaluating OGNL expression" in a simple for loop

Evaluating a postfix expression

I want to make this program shorter. Please suggest