fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static boolean isNumber(String s){
  11. try{
  12. Integer.parseInt(s);
  13. return true;
  14. }catch(Exception e){
  15. return false;
  16. }
  17. }
  18.  
  19. public static String calc(String s1, String s2, String method){
  20. String ret = "";
  21. switch(method){
  22. case "+":
  23. ret = String.valueOf(Integer.parseInt(s1) + Integer.parseInt(s2));
  24. break;
  25. case "-":
  26. ret = String.valueOf(Integer.parseInt(s1) - Integer.parseInt(s2));
  27. break;
  28. case "*":
  29. ret = String.valueOf(Integer.parseInt(s1) * Integer.parseInt(s2));
  30. break;
  31. case "/":
  32. ret = String.valueOf(Integer.parseInt(s1) / Integer.parseInt(s2));
  33. break;
  34. }
  35. return ret;
  36. }
  37.  
  38. public static void main (String[] args) throws java.lang.Exception
  39. {
  40. Stack<String> s = new Stack();
  41.  
  42. String test = "3 5 + 1 * 2 3 - -";
  43.  
  44. String[] sa = test.split(" ");
  45.  
  46. for(int i = 0; i < sa.length; i++){
  47. if(isNumber(sa[i])){
  48. s.push(sa[i]);
  49. }else{
  50. String s2 = s.pop();
  51. String s1 = s.pop();
  52. String newVal = calc(s1, s2, sa[i]);
  53. s.push(newVal);
  54. }
  55. }
  56.  
  57. System.out.println(s.pop());
  58. }
  59. }
Success #stdin #stdout 0.09s 320320KB
stdin
Standard input is empty
stdout
9