【发布时间】:2018-03-25 21:13:38
【问题描述】:
我从教科书中得到了大部分代码,而且一切似乎都在工作。例如,如果我有后缀 5 2 + 它会给我 7,这是正确的,但如果我有 5 2 4 * / 7 - 那么它会抛出非法输入异常。当我摆脱非法输入异常时,它可以工作但没有给出正确的答案。
import java.util.*;
import java.util.regex.Pattern;
//Here is my class and main method
public class postFix {
public static final Pattern UNSIGNED_DOUBLE = Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?");
public static final Pattern CHARACTER = Pattern.compile("\\S.*?");
public static Double postfixEvaluate (String expression) {
Stack<Double> numbers = new Stack<Double>( ); //Stack for numbers
Stack<Character> operators = new Stack<Character>( ); //Stack for ops
Scanner input = new Scanner(expression);
String next;
while (input.hasNext()) //Iterator is used (hasNext)
{
if (input.hasNext(UNSIGNED_DOUBLE))
{ // if next input is a number
next = input.findInLine(UNSIGNED_DOUBLE);
numbers.push(new Double(next)); //adding nums to the number stack
}
else
{ //The next input is an operator
next = input.findInLine(CHARACTER);
switch (next.charAt(0))
{
case '+':
case '-':
case '*':
case '/':
operators.push(next.charAt(0)); //adding operators to operator stack
break;
case ')':
evaluateStackTops(numbers, operators);
break;
case '(':
break;
default: //Illegal Character
throw new IllegalArgumentException("Illegal Character");
}
}
}
//This what seems to be throwing the exception but I got this right out of the book
if (numbers.size() != 1)
throw new IllegalArgumentException("Illegal Input");
return numbers.pop( );
}
public static void evaluateStackTops (Stack<Double> numbers, Stack<Character> operators)
{
double operand1 , operand2;
//check that the stacks have enough items, and get the two operands
if ((numbers.size()<2)||(operators.isEmpty())) {
throw new IllegalArgumentException("Illegal Expression");}
operand2 = numbers.pop();
operand1 = numbers.pop();
//carry out an operation based on the operator on top of the stack
for (int i = 0; i < numbers.size(); i++) {
switch (operators.pop()) {
case '+':
numbers.push(operand1 + operand2);
break;
case '-':
numbers.push(operand1 - operand2);
break;
case '*':
numbers.push(operand1 * operand2);
break;
case '/':
numbers.push(operand1 / operand2);
break;
default:
throw new IllegalArgumentException("Illegal Operator");
}
}
public static void main(String[] args) {
//String expression;
//Scanner input = new Scanner(expression);
System.out.println(postFix.postfixEvaluate("(2 3 5 * / )" ));
}
}
【问题讨论】:
-
如果你把 !=1 改成
-
不,它似乎没有读取堆栈中的所有数字和运算符。我不知道为什么它不会,除非我错过了什么
-
您期待什么答案?
5 2 4 * / 7 -是否代表中缀表达式(5 / (2 * 4)) - 7?
标签: java data-structures stack postfix-notation