簡單的回答是,「10-4」不是一個簡單的整數,這是一個計算,所以它解析爲int會沒有結果..
你必須分析你的字符串..
int aa = evaluteQuestion(questionArray[0]);
和實際的奇蹟發生在這裏:
public static int evaluteQuestion(String question){
Scanner sc = new Scanner(question);
// get the next number from the scanner
int firstValue = Integer.parseInt(sc.findInLine("[0-9]*"));
// get everything which follows and is not a number (might contain white spaces)
String operator = sc.findInLine("[^0-9]*").trim();
int secondValue = Integer.parseInt(sc.findInLine("[0-9]*"));
switch (operator){
case "+":
return firstValue + secondValue;
case "-":
return firstValue - secondValue;
case "/":
return firstValue/secondValue;
case "*":
return firstValue * secondValue;
case "%":
return firstValue % secondValue;
// todo: add additional operators as needed..
default:
throw new RuntimeException("unknown operator: "+operator);
}
}
如果你有莫在您的表達式中重新部分,您可能想要將上面的代碼放入循環中。但請注意操作順序。如果你想爲任何表達式實現合適的解析器,事情可能會變得有點多毛
如果我理解正確questionArray [0]等於「10-4」,這是一個字符串不是數字的字符串, '字符。如果我沒有記錯,ParseInt只能處理數字,不能表達。你將不得不寫一個函數,從字符串中提取第一個和第二個數字,然後按照操作符在 –
之間進行數學運算。我刪除了我的答案,現在我正在研究新的答案。保持緊張 –
爲什麼這個問題有這麼低的分數?它遵循所有的規則來提出一個好問題,而且這個問題很明顯是什麼......?夥計們,不要只是投票,至少留下一個評論..! –