1. Read the equation as a string.
2.first pop two operand from the equation
3.If the third character is an operator we do the calculate the value for that operator and the operands.
4.Then push the calculated value in to the stack.
5.finally print the final value.
Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
/** | |
* | |
* @author suthaas | |
*/ | |
import java.util.*; | |
public class postfix_calculation | |
{ | |
public static void main(String args[]) | |
{ | |
Scanner sc=new Scanner(System.in); | |
System.out.println("Enter the equation"); | |
String ex=sc.next(); | |
stack s1=new stack(ex.length()); | |
char operator; | |
int ans,a,b; | |
for(int i=0;i<ex.length();i++) | |
{ | |
operator=ex.charAt(i); | |
ans=Character.getNumericValue(operator); | |
switch( operator) | |
{ | |
case '+': a=s1.pop(); | |
b=s1.pop(); | |
ans=a+b;break; | |
case '-': a=s1.pop(); | |
b=s1.pop(); | |
ans=a-b;break; | |
case '*': a=s1.pop(); | |
b=s1.pop(); | |
ans=a*b;break; | |
case '/': a=s1.pop(); | |
b=s1.pop(); | |
ans=a/b;break; | |
} | |
s1.push(ans); | |
} | |
System.out.println(s1.pop()); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author sutha | |
*/ | |
public class stack | |
{ | |
int size; | |
int[] array; | |
int top; | |
public stack(int s) | |
{ | |
size=s; | |
top=0; | |
array=new int[s]; | |
} | |
public void push(int elt) | |
{ | |
top=top+1; | |
array[top]=elt; | |
} | |
public int pop() | |
{ | |
int mypopped=array[top]; | |
top=top-1; | |
return mypopped; | |
} | |
public boolean isEmpty() | |
{ | |
return (top==0); | |
} | |
public boolean isFull() | |
{ | |
return (top==size-1); | |
} | |
} |
0 comments:
Post a Comment