Engaged employer
Implement a function to solve an string given in reverse polish notation.
Anonymous
import java.util.StringTokenizer; import java.util.Stack; class Test{ public static void main(String arg[]) { String pf = "3 0 / "; StringTokenizer pfa = new StringTokenizer(pf," "); Stack st = new Stack(); String input=""; Double result = 0.0; while(pfa.hasMoreElements()){ try{ input = pfa.nextElement().toString(); Double num = Double.parseDouble(input); st.push(num); } catch(Exception e) { try{ Double num1 = st.pop(); Double num2 = st.pop(); if(input.equals("+")) { result = num2+num1;} else if(input.equals("-")) {result = num2-num1;} else if(input.equals("/")) {if(num1==0.0){throw new ArithmeticException();} else{result = num2/num1;}} else if(input.equals("*")) {result = num2*num1;} else {System.out.println("Not a valid input"); break;} st.push(result); continue; }catch(Exception ex){ System.out.println("Please check your input expression."); } } } System.out.println("The result : "+result); } }
Check out your Company Bowl for anonymous work chats.