-
Notifications
You must be signed in to change notification settings - Fork 0
/
Evaluate.java
48 lines (44 loc) · 1.29 KB
/
Evaluate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
Evaluation of an expression using Two Stack algorithm(DijKarta's)
*/
import java.util.Stack;
import java.util.Scanner;
class TwoStack
{
void result(String str)
{
Stack<String> ops=new Stack<String>();
Stack<Double> vals=new Stack<Double>();
Scanner sc=new Scanner(str);
while (sc.hasNext())
{ String val=sc.next();
if(val.equals("("));
else if(val.equals("+")) ops.push(val);
else if(val.equals("-")) ops.push(val);
else if(val.equals("*")) ops.push(val);
else if(val.equals("/")) ops.push(val);
else if(val.equals(")"))
{
String oper=ops.pop();
Double v=vals.pop();
if(oper.equals("+")) v+=vals.pop();
if(oper.equals("-")) v-=vals.pop();
if(oper.equals("*")) v*=vals.pop();
if(oper.equals("/")) v/=vals.pop();
vals.push(v);
}
else vals.push(Double.parseDouble(val));
}
System.out.println("Result= "+vals.pop());
}
}
class Evaluate
{
public static void main(String []args)
{
TwoStack stck=new TwoStack();
stck.result("( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) ");
stck.result("( 1 + ( ( 2 3 + ) * ( 4 5 * ) ) ) ");
stck.result(" 1 + ( 2 3 + ) * ( 4 5 * ) ");
}
}