StreamTokenizer 不会将 + 视为单词

StreamTokenizer doesn't treat + as word

在代码中

switch(token){

    case StreamTokenizer.TT_EOF:
        eof = true;
        break;
    case StreamTokenizer.TT_NUMBER:
        double value = tokenizer.nval;
        operands.add(value);
        break;
    case StreamTokenizer.TT_WORD:
        operate(tokenizer.sval);
        break;
    default:
        throw new WrongPhraseException("Unnexpected operator or operand: " + tokenizer.sval +".");
}

我给出输入 RPN,例如:5 4 3 + *

为什么 + 不被视为 TT_WORD,它不被视为 it 所以抛出异常。

来自 StreamTokenizer 文档:

For a single character token, its value is the single character, converted to an integer.

由于您的 + 字符是单个字符,它可能被视为 TT_NUMBERTT_NUMBER 的案例陈述也需要处理这些案例。我想这同样适用于您未加引号的 * 字符。因此你可以尝试这样的事情:

case StreamTokenizer.TT_NUMBER:
    Double value = new Double(tokenizer.nval);

    if (Character.isDigit(value.intValue()) {
        operands.add(value.doubleValue());

    } else {
        // Possibly dealing with operator here.  The hard/fun part is
        // in coercing that double value back to its tokenized string
        // form.
        operate(new Character((char) tokenizer.nval).toString());
    }

    break;

希望对您有所帮助!