我正在研究逆向波蘭記譜法程序,並且遇到了處理無效表達式的問題......如果運算符太少,我可以處理它,或者操作數,但我不能處理任何不是「(」,「+」,「 - 」,「*」和「#」)的字符。跳過行的其餘部分(或強制英鎊符號到輸入),而不是讀取整個表達如果接收到錯誤的字符,Java掃描儀停止讀取輸入
這裏是下面我的代碼:
public class RpnEvaluator
{
private Scanner stdin;
private Stack stack = new Stack(50);
private Queue queue = new Queue(50);
private String expression = "";
private String interValue = "";
private int numExpressions = 0;
/**
Runs the RPN Evaluator.
*/
public void run()
{
stdin = new Scanner(System.in);
while(stdin.hasNext())
{
String input = stdin.next();
if(input.charAt(0) == '(')
addOperand(input);
else if(input.equals("+") || input.equals("-") || input.equals("*"))
performOperation(input.charAt(0));
else if(input.equals("#"))
outputExpression();
else
invalidExpression(); **// Here is where I need to deal with anything that isn't above and output anything BEFORE the bad value, AND the value itself.**
}
System.out.println("Normal Termination of Program 3.");
}
例如:輸入如
(2/9) B (4/3)/#
應該返回此輸出:
Expression 1 is: (2/9)B
Invalid Expression
Intermediate results:
氮:不要說「磅符號」,如果你的意思是'#'(如你以前使用):作爲一個英國人,否則我會認爲你的意思[英鎊] //www.fileformat.info/info/unicode/char/a3/index.htm)。 –
保存輸入信息,以便在遇到錯誤字符時可以打印出導致錯誤字符的所有內容。嘗試自己填寫'invalidExpression()',看看你得到了什麼。 –
因此,輸入被自動解析爲操作符或操作數,然後放入堆棧供以後使用,但我們不應該在堆棧中放置不好的令牌,我只是想知道如何處理它。 – liquidsystem