Reputation: 59
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.
Upvotes: 0
Views: 473
Reputation: 909
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
Upvotes: 1