-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExpression.java
More file actions
126 lines (108 loc) · 3.38 KB
/
Expression.java
File metadata and controls
126 lines (108 loc) · 3.38 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import java.util.*;
import static java.lang.Character.isDigit;
/**
* Created by Devang on 06-Jan-17.
*/
public class Expression {
public static void main(String[] args){
ArrayList<String> exp = new ArrayList<>();
Scanner s = new Scanner(System.in);
System.out.println("Enter parenthesized numeric expression:?");
String input = s.nextLine();
StringTokenizer st = new StringTokenizer(input);
while(st.hasMoreElements()){
exp.add(st.nextToken());
}
System.out.println("Inflix: " + exp);
evaluate(exp);
}
private static void evaluate(ArrayList<String> exp){
Stack<String> myStack = new Stack<>();
LinkedList<String> numbers = new LinkedList<>();
Map<String, Integer> order = new LinkedHashMap<>();
order.put("-", 1);
order.put("+", 2);
order.put("*", 3);
order.put("/", 4);
order.put("^", 5);
order.put("(", 0);
order.put(")", 0);
for (String e: exp) {
if (e.equals(")")){
while(!myStack.peek().equals("(")){
numbers.add(myStack.pop());
}
myStack.pop();
}
else if(e.equals("(")){
myStack.push(e);
}
else if(isNumeric(e)){
numbers.add(e);
} else {
if(myStack.isEmpty()){
myStack.push(e);
} else {
if(order.get(myStack.peek()) > order.get(e) ){
numbers.add(myStack.pop());
myStack.push(e);
} else {
myStack.push(e);
}
}
}
}
while(!myStack.isEmpty()){
numbers.add(myStack.pop());
}
System.out.println("RPN: " + numbers);
//Calculate
while(!numbers.isEmpty()){
if(isNumeric(numbers.peekFirst())){
myStack.push(numbers.remove());
} else {
String right = myStack.pop();
String left = myStack.pop();
String operator = numbers.remove();
Double result = calc(operator, right, left);
myStack.push(result.toString());
}
}
System.out.println(myStack.peek());
}
private static double calc(String exp, String right, String left){
double result = 0.0;
double a = Double.parseDouble(left);
double b = Double.parseDouble(right);
switch (exp.toCharArray()[0]){
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '^':
result = Math.pow(a,b);
break;
}
return result;
}
private static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}