Question: JAVA Postfix The code below won't compile correctly. Error occuring on division of the 2nd expression. Please help find error. import java.util.*; public class Postfix
JAVA
Postfix
The code below won't compile correctly. Error occuring on division of the 2nd expression. Please help find error.
import java.util.*;
public class Postfix {
public static void main(String[] args) {
int data1 = 1, data2 = 2, data3 = 4, data4 = 5, data5 = 3;
String expression = String.valueOf(data1) + String.valueOf(data2) + "+" + String.valueOf(data3) + "*" + String.valueOf(data4) + "-";
System.out.println("data1 data2 + data3 * data4 - = " + postfix(expression));
String expression2 = String.valueOf(data1) + String.valueOf(data2) + "*" + String.valueOf(data3) + "*" + String.valueOf(data1) + "-" + "/" + String.valueOf(data4) + String.valueOf(data5) + "*" + "+";
System.out.println("data1 data2 * data3 * data1-/ data4 data5*+= " + postfix(expression2));
}
public static int postfix(String postfix) {
Stack
int characterCount = postfix.length();
int index = 0;
char nextChar = ' ';
Integer operandTwo, operandOne;
Integer result;
for(; index < characterCount; index++)
{
nextChar = postfix.charAt(index);
switch(nextChar)
{
case '+':
operandTwo = valuestack.pop();
operandOne = valuestack.pop();
result = operandOne + operandTwo;
valuestack.push((Integer)result);
break;
case '-':
operandTwo = valuestack.pop();
operandOne = valuestack.pop();
result = operandOne - operandTwo;
valuestack.push((Integer)result);
break;
case '*':
operandTwo = valuestack.pop();
operandOne = valuestack.pop();
result = operandOne * operandTwo;
valuestack.push((Integer)result);
break;
case '/':
operandTwo = valuestack.pop();
operandOne = valuestack.pop();
result = operandOne / operandTwo;
valuestack.push((Integer)result);
break;
default: String nextch = postfix.substring(index, index+1);
valuestack.push(Integer.parseInt(nextch));
break;
}
}
return valuestack.peek();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
