So I have slight problem that I want to fix. I have to return the result of a postfix expression, but also have to detect an invalid postfix expression. My problem is that whenever I detect the invalid postfix expression the program still returns a value for the expression. I just want to return a message stating that the expression is invalid.
Code:
public class Evaluator {
private static final String add = "+";
private static final String sub = "-";
private static final String mul = "*";
private static final String div = "/";
public static void main (String [] args) throws FileNotFoundException{
Scanner scan = new Scanner(System.in);
System.out.print("Input filename:"); // read file -------
String filename = scan.nextLine();
File file = new File(filename);
Scanner reader = new Scanner(file);// --------------------------
while (reader.hasNextLine()){
String line = reader.nextLine();
System.out.println(line + " = " + start(line));
}
}
public static int start (String line ) {
GenericStack<Integer> stack = new GenericStack<>();
String[] inputs = line.split(" ");
return postfix(stack, inputs);
}
public static int postfix(GenericStack<Integer> stack, String[] temp) {
int num1, num2;
for(int i = 0; i < temp.length; i++) {
if( temp[i].equals(add) || temp[i].equals(sub) || temp[i].equals(mul) || temp[i].equals(div) ) {
num2 = stack.pop();
num1 = stack.pop();
switch(temp[i]) {
case add: {
int operation = num1 + num2;
stack.push(operation);
break;
}
case sub: {
int operation = num1 - num2;
stack.push(operation);
break;
}
case mul: {
int operation = num1 * num2;
stack.push(operation);
break;
}
case div: {
int operation = num1 / num2;
stack.push(operation);
break;
}
}
} else {
stack.push(Integer.parseInt(temp[i]));
}
}
if (stack.isEmpty()) {
System.out.print ("No value to return on the following postfix expression: ");
}
if (stack.size() > 1) {
System.out.print ("Too many operands on the following postfix expression: ");
}
return stack.pop();
}
}
Example Output:
6 5 2 3 + 8 * + 3 + * = 288
Too many operands on the following postfix expression: 6 5 2 3 + 8 * + 3 + = 48
Best way to do this is throw Exception
Change the postfix method throw Exception on Invalid expression and add throws Exception on method signature Like below :
public static int postfix(GenericStack<Integer> stack, String[] temp) throws Exception {
....
if (stack.isEmpty()) {
throw new Exception("No value to return on the following postfix expression: ");
}
if (stack.size() > 1) {
throw new Exception("Too many operands on the following postfix expression: ");
}
}
Change start method add throws Exception on method signature
public static int start(String line) throws Exception {
....
}
And in the main method add try catch block on calling method start
try {
System.out.println(line + " = " + start(line));
} catch (Exception e) {
System.out.println(e.getMessage());
}