forked from Red-0111/Anything-Repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixEvaluation.java
105 lines (102 loc) · 2.96 KB
/
InfixEvaluation.java
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
import java.util.Stack;
public class InfixEvaluation
{
public int evaluate(String expression)
{
Stack<Integer> numbers = new Stack<>();
Stack<Character> operations = new Stack<>();
for(int i=0; i<expression.length();i++)
{
char c = expression.charAt(i);
if(Character.isDigit(c))
{
int num = 0;
while (Character.isDigit(c))
{
num = num*10 + (c-'0');
i++;
if(i < expression.length())
c = expression.charAt(i);
else
break;
}
i--;
numbers.push(num);
}
else if(c=='(')
{
operations.push(c);
}
else if(c==')')
{
while(operations.peek()!='(')
{
int output = performOperation(numbers, operations);
numbers.push(output);
}
operations.pop();
}
else if(isOperator(c))
{
while(!operations.isEmpty() && precedence(c)<=precedence(operations.peek()))
{
int output = performOperation(numbers, operations);
numbers.push(output);
}
operations.push(c);
}
}
while(!operations.isEmpty())
{
int output = performOperation(numbers, operations);
numbers.push(output);
}
return numbers.pop();
}
static int precedence(char c)
{
switch (c)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public int performOperation(Stack<Integer> numbers, Stack<Character> operations)
{
int a = numbers.pop();
int b = numbers.pop();
char operation = operations.pop();
switch (operation)
{
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
if (a == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return b / a;
}
return 0;
}
public boolean isOperator(char c)
{
return (c=='+'||c=='-'||c=='/'||c=='*'||c=='^');
}
public static void main(String[] args)
{
String infixExpression = "54 6+7 4-*9/35 15++";
InfixEvaluation i = new InfixEvaluation();
System.out.println(i.evaluate(infixExpression));
}
}