0
所以我有一个小问题,我想解决。我必须返回一个后缀表达式的结果,但也必须检测一个无效的后缀表达式。我的问题是,只要我检测到无效的后缀表达式,程序仍会返回表达式的值。我只想返回一条消息,指出表达式无效。返回后缀无效表达式
代码:
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();
}
}
示例输出:
6 5 2 3 + 8 * + 3 + * = 288
Too many operands on the following postfix expression: 6 5 2 3 + 8 * + 3 + = 48