-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
69 lines (65 loc) · 2.36 KB
/
App.java
File metadata and controls
69 lines (65 loc) · 2.36 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
import java.util.*;
public class App {
public static void main(String[] args) throws Exception {
String a = "A * B + C * D";
String b = "A + B + C * D";
String c = "A * B + ( C + A * B )";
String d = "A + ( B + C * ( A / C ) )";
String e = "A + B * C + D * E";
String f = "B * C + E ^ P + C * F";
String g = "A + B * C * D ^ P";
System.out.println("Infix: " + a + " ==> " + postFix(a));
System.out.println("Infix: " + b + " ==> " + postFix(b));
System.out.println("Infix: " + c + " ==> " + postFix(c));
System.out.println("Infix: " + d + " ==> " + postFix(d));
System.out.println("Infix: " + e + " ==> " + postFix(e));
System.out.println("Infix: " + f + " ==> " + postFix(f));
System.out.println("Infix: " + g + " ==> " + postFix(g));
}
public static String postFix(String s) {
String postfix = "";
int pCounter = 0;
int fP = s.indexOf("(");
for (int i = fP; i < s.length() && i != -1; i++) {
if (s.charAt(i) == '(') {
pCounter++;
} else if (s.charAt(i) == ')') {
pCounter--;
}
if (pCounter == 0) {
String temp = postFix(s.substring(fP + 2, i - 1));
s = s.substring(0, fP) + temp + s.substring(i + 1, s.length());
fP = s.indexOf("(");
i = fP - 1;
}
}
ArrayList<String> list = new ArrayList<>(Arrays.asList(s.split(" ")));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("^")) {
combine(list, i);
i--;
}
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("*") || list.get(i).equals("/")) {
combine(list, i);
i--;
}
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("+") || list.get(i).equals("-")) {
combine(list, i);
i--;
}
}
for (String x : list) {
postfix += x;
}
return postfix;
}
private static void combine(ArrayList<String> list, int i) {
list.set(i, list.get(i - 1) + list.get(i + 1) + list.get(i));
list.remove(i + 1);
list.remove(i - 1);
}
}