Calculator.java 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3. public class Calculator {
  4. public static void main(String[] args) {
  5. try (Scanner sc = new Scanner(System.in)) {
  6. String str = sc.nextLine();
  7. System.out.println(calculate(str));
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. private static int calculate(String str) throws Exception {
  13. char[] exp = str.toCharArray();
  14. Stack<Character> ops = new Stack<>();
  15. Stack<Integer> num = new Stack<>();
  16. // + - * / ( ) $
  17. // + > > < < < > >
  18. // - > > < < < > >
  19. // * > > > > < > >
  20. // / > > > > < > >
  21. // ( < < < < < =
  22. // E < < < < < ac
  23. for (int i = 0; i <= exp.length;) {
  24. if (i == exp.length) {
  25. if (ops.isEmpty()) break;
  26. if (ops.peek() == '(') throw new Exception("Invalid exp!");
  27. num.push(operate(ops.pop(), num.pop(), num.pop()));
  28. continue;
  29. }
  30. switch (exp[i]) {
  31. case '+': case '-':
  32. if (ops.isEmpty() || ops.peek() == '(') {
  33. ops.push(exp[i]);
  34. i++;
  35. } else {
  36. num.push(operate(ops.pop(), num.pop(), num.pop()));
  37. }
  38. break;
  39. case '*': case '/':
  40. if (ops.isEmpty() || ops.peek() == '(' || ops.peek() == '+' || ops.peek() == '-') {
  41. ops.push(exp[i]);
  42. i++;
  43. } else {
  44. num.push(operate(ops.pop(), num.pop(), num.pop()));
  45. }
  46. break;
  47. case '(':
  48. ops.push('(');
  49. i++;
  50. break;
  51. case ')':
  52. if (ops.isEmpty()) throw new Exception("Invalid exp!");
  53. if (ops.peek() == '(') {
  54. ops.pop();
  55. i++;
  56. } else {
  57. num.push(operate(ops.pop(), num.pop(), num.pop()));
  58. }
  59. break;
  60. default:
  61. int j;
  62. for (j = i + 1; j < exp.length && '0' <= exp[j] && exp[j] <= '9'; j++);
  63. int n = Integer.parseInt(str.substring(i, j));
  64. num.push(n);
  65. i = j;
  66. }
  67. }
  68. if (num.size() != 1) throw new Exception("Invalid exp!");
  69. return num.peek();
  70. }
  71. private static int operate(char op, int n2, int n1) throws Exception {
  72. switch (op) {
  73. case '+':
  74. return n1 + n2;
  75. case '-':
  76. return n1 - n2;
  77. case '*':
  78. return n1 * n2;
  79. case '/':
  80. if (n2 == 0) throw new Exception("Divided by 0!");
  81. return n1 / n2;
  82. }
  83. return 0;
  84. }
  85. }