我想創建一個簡單的計算器,根據優先級計算。該方法傳遞一個必須解決的字符串(表達式)。我這樣做的方法是首先將字符串解析爲兩個向量,一個持有數字,另一個持有操作數。在我成功解析了字符串後,我計算並返回答案。我正在使用我正在使用的掃描器類中的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;
}
有一個更好的和更優雅的方式來解析字符串(或接近的問題)?我究竟做錯了什麼?調試器沒有提供有關錯誤的更多信息。