2012-03-10 6 views
0

私は、優先順位に従って計算する単純な電卓を作成しようとしています。このメソッドには解決しなければならない文字列(式)が渡されます。私がやっているやり方は、最初に文字列を2つのベクトルに解析することです.1つは数値を保持し、もう1つはオペランドを保持します。文字列を正常に解析した後、答えを計算して返します。私は使用しているスキャナクラスから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は、Webで見つけた実装例です。がんばろう!

関連する問題