fork download
  1. class Source {
  2.  
  3. private final String str;
  4. private int pos;
  5.  
  6. public Source(String str) {
  7. this.str = str;
  8. }
  9.  
  10. public final int peek() {
  11. if (pos < str.length()) {
  12. return str.charAt(pos);
  13. }
  14. return -1;
  15. }
  16.  
  17. public final void next() {
  18. ++pos;
  19. }
  20. }
  21.  
  22. class Parser extends Source {
  23.  
  24. public Parser(String str) {
  25. super(str);
  26. }
  27.  
  28. public final int number() {
  29. StringBuilder sb = new StringBuilder();
  30. int ch;
  31. while ((ch = peek()) >= 0 && Character.isDigit(ch)) {
  32. sb.append((char) ch);
  33. next();
  34. }
  35. return Integer.parseInt(sb.toString());
  36. }
  37.  
  38. // expr = term, {("+", term) | ("-", term)}
  39. public final int expr() {
  40. int x = term();
  41. for (;;) {
  42. switch (peek()) {
  43. case '+':
  44. next();
  45. x += term();
  46. continue;
  47. case '-':
  48. next();
  49. x -= term();
  50. continue;
  51. }
  52. break;
  53. }
  54. return x;
  55. }
  56.  
  57. // term = factor, {("*", factor) | ("/", factor)}
  58. public final int term() {
  59. int x = factor();
  60. for (;;) {
  61. switch (peek()) {
  62. case '*':
  63. next();
  64. x *= factor();
  65. continue;
  66. case '/':
  67. next();
  68. x /= factor();
  69. continue;
  70. }
  71. break;
  72. }
  73. return x;
  74. }
  75.  
  76. // factor = factor = [spaces], ("(", expr, ")") | number, [spaces]
  77. public final int factor() {
  78. int ret;
  79. spaces();
  80. if (peek() == '(') {
  81. next();
  82. ret = expr();
  83. if (peek() == ')') {
  84. next();
  85. }
  86. } else {
  87. ret = number();
  88. }
  89. spaces();
  90. return ret;
  91. }
  92.  
  93. public void spaces() {
  94. while (peek() == ' ') {
  95. next();
  96. }
  97. }
  98. }
  99.  
  100. public class Main {
  101.  
  102. static void test(String s) {
  103. System.out.println(s + " = " + new Parser(s).expr());
  104. }
  105.  
  106. public static void main(String[] args) {
  107. test("1 + 2" );
  108. test("123" );
  109. test("1 + 2 + 3" );
  110. test("1 - 2 - 3" );
  111. test("1 - 2 + 3" );
  112. test("2 * 3 + 4" );
  113. test("2 + 3 * 4" );
  114. test("100 / 10 / 2" );
  115. test("( 2 + 3 ) * 4");
  116. }
  117. }
  118.  
Success #stdin #stdout 0.14s 320576KB
stdin
Standard input is empty
stdout
1 + 2 = 3
123 = 123
1 + 2 + 3 = 6
1 - 2 - 3 = -4
1 - 2 + 3 = 2
2 * 3 + 4 = 10
2 + 3 * 4 = 14
100 / 10 / 2 = 5
( 2 + 3 ) * 4 = 20