Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. import java.util.Stack;
  2. public class Question5 {
  3.  
  4. /*Stacks and Queues: Write a program evaluate arithmetical expressions
  5. * that use + and * applied to nonnegative integer arguments. Expressions are in
  6. * reverse-Polish notation, e.g., 3 4 + 5 *, 1 3 + 5 7 + *. (from EPI)
  7. */
  8.  
  9. public int evalArimathical(String s) {
  10. int answer = 0;
  11. char[] exp = s.toCharArray();
  12. int length = s.length();
  13.  
  14. Stack<Integer> eval = new Stack<Integer>();
  15. StringBuffer buff = new StringBuffer();
  16.  
  17. for (int i = 0; i < length; i++) {
  18.  
  19. if (exp[i] != '+' && exp[i] != '-' && exp[i] != '*' && exp[i] != '/') {
  20. // In case if there are more that 1 digit of the number
  21.  
  22. buff.delete(0, buff.length());
  23. // There may be more than one digits in number
  24. while (i < exp.length && exp[i] >= '0' && exp[i] <= '9')
  25. buff.append(exp[i++]);
  26.  
  27. if(buff.toString() != null) {
  28. eval.push(Integer.parseInt(buff.toString()));
  29. }
  30.  
  31. // not a number do calculation
  32. } else {
  33. int a = eval.pop();
  34. int b = eval.pop();
  35.  
  36. switch (exp[i]) {
  37. case '+':
  38. answer = a + b;
  39. break;
  40. case '-':
  41. answer = a - b;
  42. break;
  43. case '*':
  44. answer = a * b;
  45. break;
  46. case '/':
  47. answer = b/a;
  48. break;
  49. default:
  50. }
  51.  
  52. eval.push(answer);
  53. }
  54.  
  55. }
  56.  
  57. return answer;
  58.  
  59. }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement