Calculator.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 expression!");
  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. } else {
  35. num.push(operate(ops.pop(), num.pop(), num.pop()));
  36. }
  37. break;
  38. case '*': case '/':
  39. if (ops.isEmpty() || ops.peek() == '(' || ops.peek() == '+' || ops.peek() == '-') {
  40. ops.push(exp[i++]);
  41. } else {
  42. num.push(operate(ops.pop(), num.pop(), num.pop()));
  43. }
  44. break;
  45. case '(':
  46. ops.push(exp[i++]);
  47. break;
  48. case ')':
  49. if (ops.isEmpty()) throw new Exception("Invalid expression!");
  50. if (ops.peek() == '(') {
  51. ops.pop();
  52. i++;
  53. } else {
  54. num.push(operate(ops.pop(), num.pop(), num.pop()));
  55. }
  56. break;
  57. default:
  58. int j;
  59. for (j = i + 1; j < exp.length && '0' <= exp[j] && exp[j] <= '9'; j++);
  60. int n = Integer.parseInt(str.substring(i, j));
  61. num.push(n);
  62. i = j;
  63. }
  64. }
  65. if (num.size() != 1) throw new Exception("Invalid expression!");
  66. return num.peek();
  67. }
  68. private static int operate(char op, int n2, int n1) throws Exception {
  69. switch (op) {
  70. case '+':
  71. return n1 + n2;
  72. case '-':
  73. return n1 - n2;
  74. case '*':
  75. return n1 * n2;
  76. case '/':
  77. if (n2 == 0) throw new Exception("Divided by 0!");
  78. return n1 / n2;
  79. }
  80. return 0;
  81. }
  82. }