1. Construct a new method named \'evaluate\' in the program to evaluate the resu
ID: 3824741 • Letter: 1
Question
1. Construct a new method named 'evaluate' in the program to evaluate the result of the postfix string expression that is generated after converting from its infix form.
2. Add the code to call the method in main method, and also output the result to the output file 'out2a.txt'.
See the sample output below to get an idea. Postfix of the string is what, needed to be evaluated
I am providing the code that I have below, just need to add a method to evaluate the postfix expression.
Step3.java:
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class Step3
{
// Expression string
static String expression = "9.5 - 4 * 3 ^ 2 / 6 + 8 * 4";
public static void main(String[] args)
{
// Create SymbolTable object
SymbolTable st = new SymbolTable(expression);
// Printing the required information in Console
// Display my Name
System.out.println("<Exam2 : Aashiv Patel>");
// Display expression
System.out.println("Valid Expression: " + expression);
// Display operator String
System.out.println("Operator String: " + st.strOperator);
System.out.println();
// Display symbol table
System.out.println("Symbol Table: ");
System.out.println(st);
// Variable String
System.out.println("Variable String: " + st.strVariable);
// Display infix
System.out.println("Infix of the expression: " + st.buildInfix());
// Display the postfix
Step3 obj = new Step3();
System.out.println("Postfix of the expression: " + obj.infix2Postfix(expression) );
// Printing the required information in Output File
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("C:/Users/patel/Desktop/JavaFiles/out2a.txt"))))
{
// Display my Name
writer.write("<Exam2: Aashiv Patel>");
((BufferedWriter) writer).newLine();
// Display the expression
writer.write(" Valid Expression: " + expression);
((BufferedWriter) writer).newLine();
// Display the operators only
writer.write("Operator String: " + st.strOperator);
((BufferedWriter) writer).newLine();
((BufferedWriter) writer).newLine();
// Display the symbol table
writer.write("Symbol Table: ");
((BufferedWriter) writer).newLine();
// GETTING ERRORS HERE
//int size = st.size();
//for (int i = 0; i < size; i++)
//{
//writer.write(st.table);
//((BufferedWriter) writer).newLine();
//}
// Display the operands used
writer.write("Variable String: " + st.strVariable);
((BufferedWriter) writer).newLine();
// Display the infix of expression
writer.write("Infix of the expression: " + st.buildInfix());
((BufferedWriter) writer).newLine();
// Display the postfix of expression
writer.write("Postfix of the expression: " + obj.infix2Postfix(expression));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean isOperator(char c){
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
return true;
return false;
}
/**
* Checks if c2 has same or higher precedence than c1
* @param c1 first operator
* @param c2 second operator
* @return true if c2 has same or higher precedence
*/
private boolean checkPrecedence(char c1, char c2)
{
if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-'))
return true;
else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else
return false;
}
/**
* infix2Postfixs infix expression to postfix
* @param infix infix expression to be infix2Postfixed
* @return postfix expression
*/
public String infix2Postfix(String infix)
{
String postfix = ""; //equivalent postfix is empty initially
Stack<Character> s = new Stack<Character>(100); //stack to hold symbols
s.push('#'); //symbol to denote end of stack
for(int i = 0; i < infix.length(); i++)
{
char inputSymbol = infix.charAt(i); //symbol to be processed
if(isOperator(inputSymbol))
{ //if a operator
//repeatedly pops if stack top has same or higher precedence
while(checkPrecedence(inputSymbol, s.peek()))
postfix += s.pop();
s.push(inputSymbol);
}
else if(inputSymbol == '(')
s.push(inputSymbol); //push if left parenthesis
else if(inputSymbol == ')'){
//repeatedly pops if right parenthesis until left parenthesis is found
while(s.peek() != '(')
postfix += s.pop();
s.pop();
}
else
postfix += inputSymbol;
}
//pops all elements of stack left
while(s.peek() != '#')
{
postfix += s.pop();
}
return postfix;
}
public static int evaluate(String postfix)
{
// Add required code here (make new methods if required, to evaluate the expression)
}
}
Sample Output:
Valid Expression: 9.5 - 4 * 3 ^ 2 / 6 + 8 * 4
Operator String: -*^/+*
Symbol Table:
A 9.5
B 4.0
C 3.0
D 2.0
E 6.0
F 8.0
G 4.0
Variable String: ABCDEFG
Infix of the expression: A-B*C^D/E+F*G
Postfix of the expression: 9.5 4 3 2 ^* 6 /- 8 4*+
Explanation / Answer
am including just the evaluate method and all other necessary methods. The remaining part of the code should work well.
public static Double evaluate(String postfix)
{
Stack<Double> stack = new Stack<>();
int length = postfix.length();
int pos = 0;
int i;
for (i = 0; i<length; i++)
if(postfix.charAt(i)>='0' && postfix.charAt(i)>='9')
continue;
else{
if (isNumber(postfix.substring(pos, i+1).trim())){
stack.push(Double.parseDouble(postfix.substring(pos, i+1).trim()));
pos = i+1;
}
else if (postfix.substring(pos, i+1).trim().equals("*")){
double a = stack.pop();
double b = stack.pop();
stack.push(a*b);
}
else if (postfix.substring(pos, i+1).trim().equals("/")){
double a = stack.pop();
double b = stack.pop();
stack.push(a/b);
}
else if (postfix.substring(pos, i+1).trim().equals("+")){
double a = stack.pop();
double b = stack.pop();
stack.push(a+b);
}
else if (postfix.substring(pos, i+1).trim().equals("-")){
double a = stack.pop();
double b = stack.pop();
stack.push(a-b);
}
else if (postfix.substring(pos, i+1).trim().equals("^")){
double a = stack.pop();
double b = stack.pop();
stack.push(Math.pow(a, b));
}
}
if (postfix.substring(pos, i+1).trim().equals("*")){
double a = stack.pop();
double b = stack.pop();
stack.push(a*b);
}
else if (postfix.substring(pos, i+1).trim().equals("/")){
double a = stack.pop();
double b = stack.pop();
stack.push(a/b);
}
else if (postfix.substring(pos, i+1).trim().equals("+")){
double a = stack.pop();
double b = stack.pop();
stack.push(a+b);
}
else if (postfix.substring(pos, i+1).trim().equals("-")){
double a = stack.pop();
double b = stack.pop();
stack.push(a-b);
}
else if (postfix.substring(pos, i+1).trim().equals("^")){
double a = stack.pop();
double b = stack.pop();
stack.push(Math.pow(a, b));
}
return stack.pop();
}
private static boolean isNumber(String str){
try{
Double.parseDouble(str);
} catch (NumberFormatException e){
return false;
}
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.