Hi all - I am writing a program that uses two classes: One class is the InfixtoPostfix, which is actually the class that changes expressions from infix to postfix. (Example: ( A + B ) * ( C - D ) to
A B + C D -*. The second class, PostfixEval, is supposed to calculate the expression.
My problem is that my code works easily enough for expressions with values (Example: ( 1 + 2 ) * ( 3 - 4 ), but the file we have to read in is variables. We were given a list of values (Example: A = 12, B = 22, C = -5, etc.), to assign to the variables and hard code. So I guess my question is how can I edit my code so that it assigns a value to the variable and calculates the postfix expressions?
Here's my infix to postfix class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class InfixtoPostfix {
public static final String operators = "+-*/";
public static final String left = "(";
public static final String right = ")";
public static void main(String[] args){
File file = new File("infix.txt");
try{
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String line = sc.nextLine();
System.out.println("Postfix:" + " " + convert(line));
String finalResult = convert(line);
System.out.println("Result:" + " " + PostfixEval.evaluate(finalResult));
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
public static String convert(String str){
String conversion = "";
Stack<Character> stuff = new Stack<Character>();
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
if(c==('+')||c==('*')||c==('-')||c==('/')){
while(!stuff.empty() && isLower(stuff.peek(), c))
conversion+=stuff.pop();
stuff.push(c);
}
else if(c=='('){
stuff.push(c);
}
else if(c==')'){
while(!stuff.peek().equals('('))
conversion += stuff.pop();
stuff.pop();
}
else
conversion += c;
}
while(!stuff.empty())
conversion+=stuff.pop();
return conversion;
}
public static boolean isLower(char c1, char c2){
if((c1 == '+' || c1 == '-') && (c2 == '*' || c2 == '/'))
return true;
return false;
}
}
and here is my postfix evaluator class
import java.util.Stack;
public class PostfixEval{
public static Double evaluate(String postfix){
Stack<Double> s = new Stack<Double>();
char[] chars = postfix.toCharArray();
int N = chars.length;
for(int i = 0; i < N; i++){
char ch = chars[i];
if(isOperator(ch)){
switch(ch){
case '+': s.push(s.pop() + s.pop()); break;
case '*': s.push(s.pop() * s.pop()); break;
case '-': s.push(-s.pop() + s.pop()); break;
case '/': s.push(1 / s.pop() * s.pop()); break;
}
}else if(Character.isDigit(ch)) {
s.push(0.0);
while (Character.isDigit(chars[i]))
s.push(10.0 * s.pop() + (chars[i++] - '0'));
}
}
if (!s.isEmpty())
return s.pop();
else
return 0.0;
}
private static boolean isOperator(char ch) {
return ch == '*' || ch == '/' || ch == '+' || ch == '-';
}
}