I know how to convert to infix to postfix but cant evaluate the result please help
Code:import java.util.*; class term {public term next; public Object data; public term() {data=' '; next=null; } public term(Object val) {data = val; next = null; } } public class intopost {private term top; public intopost(){top = null;} public boolean empty(){ return top == null; } public boolean full(){return false;} public void push(Object e){ term tmp = new term(e); tmp.next = top; top = tmp; } public Object pop() {Object e = top.data; top = top.next; return e; } public Object peek() {Object e=top.data; return e; } public void matching(String x) {Stack s=new Stack(); for(int i=0;i<x.length();i++) {char c=x.charAt(i); if(c=='(') s.push(c); else {if(c==')') if(s.empty()) matching=false; else s.pop(); } } if(!s.empty()) matching=false; } public void Evaluation(String x) {int i,z,u; char c; intopost S=new intopost(); for(i=0;i<x.length();i++) {c=x.charAt(i); String s="0"+c; if(c=='+') { z=Integer.parseInt((String)S.pop())+Integer.parseInt((String)S.pop()); S.push(Integer.toString(z)); } else if(c=='*') { z=Integer.parseInt((String)S.pop())*Integer.parseInt((String)S.pop()); S.push(Integer.toString(z)); } else if(c=='/') {u=Integer.parseInt((String)S.pop()); z=Integer.parseInt((String)S.pop())/u; S.push(Integer.toString(z)); } else if(c=='-') {u=Integer.parseInt((String)S.pop()); z=Integer.parseInt((String)S.pop())-u; S.push(Integer.toString(z)); } else S.push(s); } System.out.println("THE POSTFIX = "+x); System.out.println("THE RESULT = "+S.pop()); } public String postfix(String x) { String output=""; intopost S=new intopost(); for(int i=0;i<x.length();i++) {char c=x.charAt(i); if(c==('+')||c==('*')||c==('-')||c==('/')) {while(!S.empty() && priority(S.peek())>= priority(c)) output+=S.pop(); S.push(c); } else if(c=='(') S.push(c); else if(c==')') { while(!S.peek().equals('(')) output+=S.pop(); S.pop(); } else output+=c; } while(!S.empty()) output+=S.pop(); return output; } public int priority(Object x) { if(x.equals('+')||x.equals('-')) return 1; else if(x.equals('*')||x.equals('/')) return 2; else return 0;} public static boolean matching=true; public static void main(String args[]) { intopost e=new intopost(); String infix,post; System.out.println("enter equation in ifix form"); Scanner in=new Scanner(System.in); infix=in.next(); post=e.postfix(infix); System.out.println("THE POSTFIX = "+post); e.matching(infix); e.Evaluation(infix); } }
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks