Repository navigation
Expand file tree
/
Copy pathPostFix.java
More file actions
115 lines (100 loc) · 2.92 KB
/
Copy pathPostFix.java
File metadata and controls
115 lines (100 loc) · 2.92 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
import java.util.*;
public class PostFix {
public int evaluateFix (String exp) {
// Stack
Stack<Integer> stack = new Stack<>();
// Looks through each character
for(int i = 0; i < exp.length(); i++)
{
char op = exp.charAt(i);
// If the character isDigit, push it to the stack
if (Character.isDigit(op))
stack.push(op - '0');
// Else, pop two
else
{
int first = stack.pop();
int second = stack.pop();
switch(op) {
case'+':
stack.push(second+first);
break;
case'-':
stack.push(second-first);
break;
case'*':
stack.push(second*first);
break;
case'/':
stack.push(second/first);
break;
} //Switch end
} //Else end
} //Forloop end
return stack.pop();
} // evaluteFix end
// Checks operand (+, -, *, /, ^) precedence
public static int Weight(char op) {
switch(op) {
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}// Switch end
} // end of class
static String postFix(String exp) {
Stack<Character> stack = new Stack<Character>();
String postfix = "";
for (int i = 0; i < exp.length(); i++) {
char op = exp.charAt(i);
if(Weight(op) > 0) {
while (stack.isEmpty() == false &&
Weight (stack.peek()) >= Weight(op)) {
postfix += stack.pop();
}
stack.push(op);
}
else if(op==')') {
char s = stack.pop();
while(s!='('){
postfix += s;
s = stack.pop();
}
}
else if(op=='('){
stack.push(op);
} else {
postfix += op;
}
} // end of loop
for (int i = 0; i <= stack.size(); i++) {
postfix += stack.pop();
} // end of loop
return postfix;
} //End postFix class
//Testing
public static void main(String[] args) {
// Ask user for infix expression
System.out.println("Type your infix expression!");
Scanner scanner = new Scanner( System. in);
String exp = scanner.nextLine();
// Displays infix expression
System.out.println("Infix Expression: " + exp);
// Displays postfix expression
String O = postFix(exp);
System.out.println("Postfix expression: " + O);
// Create instance of PostFix
PostFix pf = new PostFix();
int result = pf.evaluateFix(O);
//Calulate Values
System.out.println("Postfix Value: " + result);
}
} // Class end