2012-03-10 57 views
0

我想創建一個簡單的計算器,根據優先級計算。該方法傳遞一個必須解決的字符串(表達式)。我這樣做的方法是首先將字符串解析爲兩個向量,一個持有數字,另一個持有操作數。在我成功解析了字符串後,我計算並返回答案。我正在使用我正在使用的掃描器類中的java.util.InputMismatchException。這裏是我的代碼:簡單的計算器使用Java掃描儀和矢量類

public static int performCalc(String problem) 
{ 
    // 3 * 2 + 4/1 + 2 + 4 
    Pattern op = Pattern.compile("[*/+-]"); 
    String prob; 
    Vector<Integer> nums = new Vector(); 
    Vector<String> operands = new Vector(); 
    int answer = 0, index = 0, numOne, numTwo; 
    Scanner scNums = new Scanner(problem); 
    Scanner scOperands = new Scanner(problem); 
    while(scNums.hasNext()) 
    { 
     nums.add(scNums.nextInt()); 
    } 
    while(scNums.hasNext()) 
    { 
     operands.add(scNums.next(op)); 
    } 
    for(int i = 0; i<operands.size(); i++) 
    { 
     if(operands.get(i) == "*" || operands.get(i) == "/") 
     { 
      nums.set(i, calc(nums.get(i), operands.get(i), nums.get(i+1))); 
      nums.remove(i+1); 
     } 
    } 
    for(int i = 0; i<operands.size(); i++) 
    { 
     if(operands.get(i) == "+" || operands.get(i) == "-") 
     { 
      nums.set(i, calc(nums.get(i), operands.get(i), nums.get(i+1))); 
      nums.remove(i+1); 
     } 
    } 
    return nums.firstElement(); 
} 
public static int calc(int numOne, String operand, int numTwo) 
{ 
    if(operand == "*") 
     return numOne*numTwo; 
    if(operand == "/") 
     return numOne/numTwo; 
    if(operand == "+") 
     return numOne+numTwo; 
    if(operand == "-") 
     return numOne-numTwo; 
    return 0; 
} 

有一個更好的和更優雅的方式來解析字符串(或接近的問題)?我究竟做錯了什麼?調試器沒有提供有關錯誤的更多信息。

回答

0

林不知道這是否是問題,但不應該在第二個的代碼,而循環是

while(scOperands.hasNext()) 
0

在第一循環

while(scNums.hasNext()) 

你是從輸入參數讀取數據(問題)我認爲你傳遞了整數和操作數的字符串(類似「3 * 2 +」)。所以當你在符號「*」上調用nextInt時,你得到了InputMismatchException。

也許你想寫這樣的事情(注意 - 如果有奇數個輸入參數的跡象會發生什麼):

Scanner scanner = new Scanner(problem); 
while(scanner.hasNext()) 
{ 
    nums.add(scanner.nextInt()); 
    operands.add(scanner.next(op)); 
} 
0

我個人會用Reverse Polish Notation(RPN)。起初可能會讓人困惑,但一旦理解了語法,就很容易用堆棧實現。您無需處理掃描器,您的輸入可以像分隔字符串一樣簡單。 Here是我在網上找到的一個示例實現。祝你好運!