2015-10-14 52 views
0

我正在研究逆向波蘭記譜法程序,並且遇到了處理無效表達式的問題......如果運算符太少,我可以處理它,或者操作數,但我不能處理任何不是「(」,「+」,「 - 」,「*」和「#」)的字符。跳過行的其餘部分(或強制英鎊符號到輸入),而不是讀取整個表達如果接收到錯誤的字符,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: 
+2

氮:不要說「磅符號」,如果你的意思是'#'(如你以前使用):作爲一個英國人,否則我會認爲你的意思[英鎊] //www.fileformat.info/info/unicode/char/a3/index.htm)。 –

+0

保存輸入信息,以便在遇到錯誤字符時可以打印出導致錯誤字符的所有內容。嘗試自己填寫'invalidExpression()',看看你得到了什麼。 –

+0

因此,輸入被自動解析爲操作符或操作數,然後放入堆棧供以後使用,但我們不應該在堆棧中放置不好的令牌,我只是想知道如何處理它。 – liquidsystem

回答

0

兮兮的筆記後,我發現,我們首先介紹了逆波蘭式,我們確實談到了處理一節可能的錯誤,從這些筆記中,我創建了這兩種方法,看起來完美無缺。

private void skipExpression() 
{ 
    while(stdin.hasNext()) 
    { 
     input = stdin.next(); 
     if(input.equals("#")) 
     break; 
    } 
} 

private void invalidExpression() 
{ 
    skipExpression(); 
    numExpressions++; 
    System.out.println("Expression " + numExpressions + " is: " + expression); 
    System.out.println("Invalid Expression"); 
    System.out.println("Intermediate results: " + interValue); 
    expression = ""; 
    interValue = ""; 
    stack.clear(); 
    queue.clear(); 
} 
0

我會與hasNext(Pattern pattern)在第一測試如果下列令牌是與具有相同特定上下文[0-9+/*\-#]或一個以上的圖案有效的,並且如果不是我將跳過(模式圖案)與模式匹配每字符但回車,它.確實

+0

謝謝你的迴應,但是我們沒有談論過使用'.hasNext()'和任何形式的參數,下面給出的答案是這樣做的,甚至如果這不是最好的解決方案。 – liquidsystem