import java.io.*; import java.util.*; /* 6 4 3 + + 3 8 2 * + * 2 + 3 + 9 6 2 * 7 * 12 5 9 6 - * + * + 1 2 - 4 5 $ 3 * 6 * 7 2 2 $ $ / - 8 2 5 + * 2 / 4 $ 6 3 12 * / - */ public class Lab7 { private String filename; public static void main(String args[]) { Lab7 l = new Lab7(); l.requestFile(); try { BufferedReader br = new BufferedReader(new FileReader(l.getFilename())); String line = ""; while( ((line = br.readLine()) != null) ) { boolean goodline = true; StackArrayBased s = new StackArrayBased(); String tokLine = ""; StringTokenizer tok = new StringTokenizer(line); while(tok.hasMoreTokens()) { tokLine = tok.nextToken().trim(); //System.out.println("tok> " + tokLine); if( (tokLine.equalsIgnoreCase("+")) || (tokLine.equalsIgnoreCase("-")) || (tokLine.equalsIgnoreCase("*")) || (tokLine.equalsIgnoreCase("/")) || (tokLine.equalsIgnoreCase("$")) ) { //System.out.println("Symbol> " + tokLine); // if(!s.isEmpty()) { //6 4 3 + + 3 8 2 * + * 2 + 3 + Integer i = (Integer)s.pop(); int temp1 = i.intValue(); //System.out.println("POP> " + i); if(!s.isEmpty()) { i = (Integer)s.pop(); } else { System.out.println("Stack is empty,,, program terminated"); System.exit(-1); } int temp2 = i.intValue(); //System.out.println("POP> " + i); int temp3 = 0; if(tokLine.equalsIgnoreCase("+")) { temp3 = temp2 + temp1; } else if(tokLine.equalsIgnoreCase("-")) { temp3 = temp2 - temp1; } else if(tokLine.equalsIgnoreCase("*")) { temp3 = temp2 * temp1; } else if(tokLine.equalsIgnoreCase("/")) { temp3 = temp2 / temp1; } else if(tokLine.equalsIgnoreCase("$")) { temp3 = (int)Math.pow((double)temp2,(double)temp1); } else { System.out.println("Incorrect Symbol"); } s.push(new Integer(temp3)); } // } else if(tokLine.equalsIgnoreCase("")) { System.out.println("End of line reached"); goodline = false; } else { if(!s.isFull()) { int t = Integer.parseInt(tokLine); //System.out.println("PUSH> " + t); s.push(new Integer(t)); } } } if(goodline) { ///this is the last one Integer j = (Integer)s.pop(); int temp4 = j.intValue(); System.out.println(line + "\tvalue of postfix expression is " + temp4); System.out.println(); //System.out.println("Value Is> " + temp4); } else { System.out.println("a blank line was encountered"); } } } catch(Exception e) { System.out.println("Error> " + e); } } public Lab7() { filename = ""; } public void setFilename(String f) { filename = f; } public String getFilename() { return filename; } public void requestFile() { String file = ""; try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Filename> "); //file = br.readLine(); file = "C:\\Johnny\\School\\cs2003\\lab7\\postfix.dat"; setFilename(file); } catch(Exception e) { System.out.println("Error> " + e); } } }