Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Test
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
/** Mathematical Expression Evaluator using two Stacks Version: 1.1 */ import java.util.*; import java.lang.*; class Rextester { static List<Character> precedence; public static void main(String args[]) throws Exception { precedence = new ArrayList<Character>(); precedence.add('+'); precedence.add('-'); precedence.add('*'); precedence.add('/'); String expr = "-5+8*9"; System.out.println(expr + " = " + evaluate(expr)); } private static int evaluate(String expr) throws Exception { Stack<Character> opStack = new Stack<Character>(); Stack<Integer> valueStack = new Stack<Integer>(); char[] tokens = expr.toCharArray(); for(Character c : tokens) { if(c == ' ') continue; if(c >= '0' && c <= '9') { // digit valueStack.push(Integer.parseInt(c.toString())); } else { // operator while(!opStack.isEmpty() && hasprecedence(c, opStack.peek())) { valueStack.push(getValue(valueStack.pop(), valueStack.pop(), opStack.pop())); } opStack.push(c); } //System.out.println(valueStack); } while(!opStack.isEmpty()) { valueStack.push(getValue(valueStack.pop(), valueStack.pop(), opStack.pop())); //System.out.println("ok: " + valueStack); } // Last value in valueStack is final answer if(!valueStack.isEmpty()) return valueStack.pop(); return 0; } /** Check if op2 has higher precedence than op1 */ private static boolean hasprecedence(char op1, char op2) { return precedence.indexOf(op2) >= precedence.indexOf(op1); } private static int getValue(int val1, int val2, char op) throws Exception { int result = 0; switch(op) { case '+': result = val1 + val2; break; case '-': result = val2 - val1; break; case '*': result = val1 * val2; break; case '/': if(val1 == 0) { throw new Exception("divide by zero"); } result = val2 / val1; } return result; } }
[
+
]
Show input
Compilation time: 0.94 sec, absolute running time: 0.14 sec, cpu time: 0.1 sec, memory peak: 33 Mb, absolute service time: 1.11 sec
edit mode
|
history
|
discussion
2 - 4 * 2 = -6