This repository was archived by the owner on Feb 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.java
More file actions
97 lines (72 loc) · 2.21 KB
/
postfix.java
File metadata and controls
97 lines (72 loc) · 2.21 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
import java.util.*;
public class postfix {
public static void main(String[] args) {
System.out.println("ENTER THE EQUATION IMMEDIATLEY");
Scanner sc=new Scanner(System.in);
String equation=sc.nextLine();
Stack<String> op=new Stack<String>();
Stack<Integer> nums=new Stack<Integer>();
System.out.println("---Evaluating your equation right now---");
String current="";
String chara;
try {
for(int i=0;i<equation.length();i++) {
chara=Character.toString(equation.charAt(i));
System.out.println("PROCESSING CHAR "+chara);
if(chara.equals("+")) {
op.push(chara);
}else if(chara.equals("-")) {
op.push(chara);
i++;
}
else if(chara.equals("*")) {
op.push(chara);
i++;
}
else if(chara.equals("/")) {
op.push(chara);
i++;
}else if(chara.equals("%")) {
op.push(chara);
i++;
}else if(chara.equals(" ")){
try{
nums.push(Integer.parseInt(current));
}catch(Exception e) {
throw new Exception("INVALID OPERATOR");
}
current="";
}else {//It's a number
current=current+chara;
}
}
if(nums.size()!=(op.size()+1)) {
throw new Exception("NOT ENOUGH OPERATORS");
}
int result,num;
String o;
result=nums.pop();
System.out.println("Almost done calculating");
System.out.println(nums.size()+" "+op.size());
for(int i=0;i<nums.size();i++) {
num=nums.pop();
o=op.pop();
System.out.println(num);
if(o.equals("*")){
result=result*num;
}else if(o.equals("/")) {
result=result/num;
}else if(o.equals("+")) {
result=result+num;
}else if(o.equals("-")) {
result=result*num;
}else if(o.equals("%")) {
result=result%num;
}
}
System.out.println("CALC:"+result);
}catch(Exception e) {
System.out.println("YOU HAVE JUST VOIDED THE WARRANTY ERROR:"+e.getMessage());
}
}
}