我在將字串運算式中的正數與負數相乘時遇到問題。
如果我的運算式是-4*5那么它回傳-20,但如果我把4*-5它回傳-5 而不是-20。
我做了一些除錯,發現我的子字串只選擇了 -5 但 * 運算子后面沒有數字所以它回傳 0.0
我想在運算式執行之前檢查負號并確定它是否是負數。然而,它并沒有像預期的那樣。
我能得到一些幫助嗎?
if (expression.contains("-"))
{
int indexOfExpression = expression.lastIndexOf('-');
String beforeMinus = expression.substring(indexOfExpression-1,indexOfExpression);
if(beforeMinus.equals("*") || beforeMinus.equals("/"))
{
double afterMinus = Double.parseDouble(expression.substring(indexOfExpression,indexOfExpression 2));
return afterMinus;
}else {
double rhs = evaluate(expression.substring(indexOfExpression 1));
return evaluate(expression.substring(0, indexOfExpression)) - rhs;
}
} else if (expression.contains("*")) {
int indexOfExpression = expression.lastIndexOf("*");
Double rhs = evaluate(expression.substring(indexOfExpression 1));;
return evaluate(expression.substring(0, indexOfExpression)) *rhs;
}
這是我目前擁有的,輸出是-5而不是-20。
uj5u.com熱心網友回復:
代碼中有很多錯誤,所以我認為從如何更好地完成而不是僅僅除錯的角度來回答更有意義。我假設您要執行由四個運算子之一分隔的兩個數字的二元運算 , -, *, /。主要困難是-作為運算子和-作為負數符號之間的歧義(在這種情況下,它更像是乘法而-1不是減法)。以下并不是一個防彈演算法,而是讓您了解解決問題的更結構化的方法。
class Operator {
public String op;
public int index;
}
Operator findOperator(String expression) {
// Assumes that 'expression' is a simple expression of the form:
// <number><op><number>
// Find all instances of ' ', '-', '*', '/'.
// If '-' appears one or more times with another symbol, the other one is
// the operator. If more than one '-' appears, determine which is the
// operator based on position (e.g. can't be the operator at index zero).
return new Operator(...);
}
double calculate(String op, String lhs, String rhs) {
double left = Double.parseDouble(lhs);
double right = Double.parseDouble(rhs);
switch (op) {
case " ":
return left right;
// etc.
}
}
double calculate(String expression) {
Operator operator = findOperator(expression);
return calculate(
operator.op,
expression.substring(0, operator.index),
expression.substring(operator.index 1));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/410747.html
標籤:
上一篇:為什么在Android模擬器中點擊除錯時ReactNative應用程式崩潰?
下一篇:從字串中獲取int陣列
