// Java program to evaluate an expression using Postfix evaluation method
import java.util.Stack;
import java.lang.*;
public class posteval
{
// Driver program to test above functions
public static void main(String[] args)
{
String exp="4542^+*22^93/*-";
System.out.println("postfix evaluation: "+evaluatePostfix(exp));
}
// Method to evaluate value of a postfix expression
static int evaluatePostfix(String exp)
{
//create a stack
Stack<Integer> stack=new Stack<>();
// Scan all characters one by one
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
// If the scanned character is an operand (number here),
// push it to the stack.
if(Character.isDigit(c))
stack.push(c - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch(c)
{
case '^':
stack.push((int) Math.pow(val2,val1)); // boxing= converting the data type of double datattype into int datatype
break;
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
}
Output:
import java.util.Stack;
import java.lang.*;
public class posteval
{
// Driver program to test above functions
public static void main(String[] args)
{
String exp="4542^+*22^93/*-";
System.out.println("postfix evaluation: "+evaluatePostfix(exp));
}
// Method to evaluate value of a postfix expression
static int evaluatePostfix(String exp)
{
//create a stack
Stack<Integer> stack=new Stack<>();
// Scan all characters one by one
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
// If the scanned character is an operand (number here),
// push it to the stack.
if(Character.isDigit(c))
stack.push(c - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch(c)
{
case '^':
stack.push((int) Math.pow(val2,val1)); // boxing= converting the data type of double datattype into int datatype
break;
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
}
Output:
No comments:
Post a Comment