-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRPNGenerator.java
More file actions
108 lines (99 loc) · 3.16 KB
/
Copy pathRPNGenerator.java
File metadata and controls
108 lines (99 loc) · 3.16 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
package inter;
import javax.naming.OperationNotSupportedException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.zip.DataFormatException;
public class RPNGenerator {
private TArrayStack<Character> stack;
private StringBuilder str;
public RPNGenerator(int stackSize){
stack = new TArrayStack<Character>(stackSize > 126 ? stackSize : 256);
str = new StringBuilder();
}
public String generate(String fileName) {
str.setLength(0);
try (FileInputStream fin = new FileInputStream(fileName)) {
Scanner sc = new Scanner(fin);
while (sc.hasNext()) {
String word = sc.next();
char sign = word.charAt(0);
if (sign == '(') {
stack.push(sign);
} else if (sign == ')') {
removeUntillBracker();
} else if (numberOrVariable(sign)) {
str.append(word).append(" ");
} else if (operation(sign)) {
pushOperationToStack(sign);
} else {
throw new DataFormatException();
}
}
while (!stack.isEmpty()) {
str.append((stack.pop())).append(" ");
}
return str.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DataFormatException e) {
e.printStackTrace();
} catch (OperationNotSupportedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "err";
}
private void pushOperationToStack(char sign) throws OperationNotSupportedException{
while(!stack.isEmpty()){
if(priority(sign) > priority(stack.top())){
stack.push(sign);
return;
}else{
str.append(stack.pop()).append(" ");
}
}
stack.push(sign);
}
private int priority(char sign) throws OperationNotSupportedException{
switch(sign){
case '(': return 0;
case '+':
case '-':
case ')': return 1;
case '*':
case '/':
case '%': return 2;
default:throw new OperationNotSupportedException();
}
}
private boolean operation(char sign){
switch(sign){
case '+':
case '-':
case '/':
case '%':
case '*': return true;
default: return false;
}
}
private boolean numberOrVariable(char sign){
if(Character.isLetter(sign)||Character.isDigit(sign))
return true;
else
return false;
}
public void removeUntillBracker() throws DataFormatException{
while(!stack.isEmpty() ){
if(stack.top() == '(' ){
stack.pop();
return;
}else{
str.append(stack.pop()).append(" ");
}
}
throw new DataFormatException();
}
}