我正在嘗試從字串中添加一些數字例如字串是“5 3 2”。這應該回傳 10 這是我獲取運算子編號的代碼是“ ”
int opIndex= expression.indexOf(" ");
Double lhs = Double.parseDouble(expression.substring(0, opIndex));
Double rhs = Double.parseDouble(expression.substring(opIndex 1));
我得到的回報是 lhs = 5 (這就是我想要的) rhs = 回傳了一個字串錯誤(3 2);
我怎樣才能在 (5 3) 或任何其他方法之后才獲得 3 號 2 ?
謝謝。
uj5u.com熱心網友回復:
如果您使用事物串列遞回地執行操作,請始終按照以下模式思考:
- 處理串列的第一個元素
- 使用遞回呼叫處理串列的其余部分
因此,在 的情況下"5 3 2",拆分5," "然后將其余 ( "3 2") 再次傳遞給相同的方法。
在開始之前洗掉空格也容易得多。
public static void main(String[] args) {
String input = "5 3 2";
//remove spaces:
input = input.replaceAll(" ", "");
int r = evaluate(input);
System.out.println(r);
}
private static int evaluate(String s) {
int operatorIndex = s.indexOf(' ');
if(operatorIndex == -1) {
//no operator found, s is the last number
//this is the base case that "ends" the recursion
return Integer.parseInt(s);
}
else {
//this is left hand side:
int operand = Integer.parseInt(s.substring(0, operatorIndex));
//this performs the actual addition of lhs and whatever rhs might be (here's where recursion comes in)
return operand evaluate(s.substring(operatorIndex 1));
}
}
此代碼列印10. 如果您還想支持減法,它會變得更加復雜,但您會弄清楚的。
uj5u.com熱心網友回復:
您可以使用 split 方法拆分彈簧
String array[]=expression.split(" ")
現在迭代陣列,你可以
uj5u.com熱心網友回復:
"RHS" 字串最終會變成" 3 2". 您的作業不是得到 3。您的作業是遞回:將該字串提供給您自己的演算法,相信它有效。
這就是遞回的作業原理:假設你的演算法已經作業,然后你撰寫它,呼叫你自己,附加規則你只能用“更簡單”的情況呼叫你自己(因為否則它永遠不會結束),并且你撰寫代碼來顯式處理最簡單的情況(在這種情況下,如果我只給你的方法一個數字,大概是這樣。如果我給它"5",它需要回傳 5,而不是遞回)。
uj5u.com熱心網友回復:
您可以使用split() 或 -:
String[] terms = expression.split("[- ]");
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411302.html
標籤:
上一篇:通過多個匹配條件遞回過濾無限嵌套物件陣列,但僅回傳具有兩個匹配實體的父物件
下一篇:歸并排序中的遞回和While回圈
