?int multiplyIndex = str.indexOf("x");? ? ? int divideIndex = str.indexOf("÷");? ? ? int firstOperationIndex = -1;? ? ? if (multiplyIndex == -1) firstOperationIndex = divideIndex;? ? ? if (divideIndex == -1) firstOperationIndex = multiplyIndex;? ? ? if (firstOperationIndex == -1) firstOperationIndex = Math.min(multiplyIndex, divideIndex);? ? ? String operation = str.substring(firstOperationIndex, firstOperationIndex+1);? ? ? String leftE = str.substring(0, firstOperationIndex-1);? ? ? String rightE = str.substring(firstOperationIndex+2);其中,str是例如“1+2+3x4+7”之類的字符串
1 回答
已采納

習(xí)慣受傷
TA貢獻(xiàn)885條經(jīng)驗(yàn) 獲得超1144個(gè)贊
//舉例:str?=?1+2+3x4+7 //從字符串中查找“x”符號(hào)位置 //例子解析:x的位置為:5,所以?multiplyIndex=5 int?multiplyIndex?=?str.indexOf("x"); //從字符串中查找“÷”符號(hào)位置 //例子解析:str中沒有÷符號(hào),所以?divideIndex=-1 int?divideIndex?=?str.indexOf("÷"); //待計(jì)算的第一個(gè)操作索引 int?firstOperationIndex?=?-1; //如果沒有找到乘法符號(hào)索引,那么第一個(gè)操作索引就賦值為除法符號(hào)索引 //例子解析:multiplyIndex?!=?-1,所以這句不執(zhí)行 if?(multiplyIndex?==?-1)? firstOperationIndex?=?divideIndex; //如果沒有找到除法符號(hào)索引,那么第一個(gè)操作索引就賦值為乘法符號(hào)索引 //例子解析:divideIndex?==?-1,所以?firstOperationIndex?=?5 if?(divideIndex?==?-1)? firstOperationIndex?=?multiplyIndex; //如果既沒有找到乘法符號(hào)也沒有找到除法符號(hào)索引,那么判斷它們之間最小的索引值。 //例子解析:firstOperationIndex?!=?-1,所以這句不執(zhí)行 if?(firstOperationIndex?==?-1)? firstOperationIndex?=?Math.min(multiplyIndex,?divideIndex); //查找計(jì)算符號(hào) //例子解析:執(zhí)行這句之后,operation="x" String?operation?=?str.substring(firstOperationIndex,?firstOperationIndex+1); //取操作符號(hào)左側(cè)字符串 String?leftE?=?str.substring(0,?firstOperationIndex-1); //取操作符號(hào)右側(cè)字符串 String?rightE?=?str.substring(firstOperationIndex+2);
添加回答
舉報(bào)
0/150
提交
取消