forked from sunnyshahabuddin/Coding-Ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposteval.java
More file actions
72 lines (72 loc) · 1.14 KB
/
posteval.java
File metadata and controls
72 lines (72 loc) · 1.14 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
import java.io.*;
import java.util.*;
import java.lang.*;
class stack
{
int[] arr;
int top,size;
stack(int n)
{
arr=new int[n];
top=-1;
size=n;
}
public void push(int f)
{
arr[++top]=f;
}
public int pop()
{
return arr[top--];
}
public int peek()
{
return arr[top];
}
public boolean isempty()
{
return top==-1;
}
}
class eval
{
stack sk=new stack(40);
void evaluate(String exp)
{try{
for(int i=0;i<exp.length();i++)
{
char s=exp.charAt(i);
if(Character.isDigit(s))
sk.push(Integer.parseInt(""+s));
else
{
int val1=sk.pop();
int val2=sk.pop();
switch(s)
{
case '+':sk.push(val1+val2);
break;
case '-':sk.push(val1-val2);
break;
case '*':sk.push(val1*val2);
break;
case '/':sk.push(val1/val2);
break;
}
}
}
System.out.println("Result : "+sk.pop());
}
catch (Exception e){System.out.println("Invalid Expression");}
}}
class posteval
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
eval sk=new eval();
System.out.println("ENTER POSTFIX EXPRESSION");
String exp=sc.nextLine();
sk.evaluate(exp);
}
}