这个问题在这里已有答案:
我正在尝试用Java编写一个程序,它接受输入一个像 s = "1+27-63*5/3+2" 这样的字符串值并以整数值返回计算
Here below is my code
package numberofcharacters;
import java.util.ArrayList;
public class App {
public static void main(String[] args) {
String toCalculate = "123+98-79÷2*5";
int operator_count = 0;
ArrayList<Character> operators = new ArrayList<>();
for (int i=0; i < toCalculate.length(); i++){
if (toCalculate.charAt(i) == '+' || toCalculate.charAt(i) == '-' ||
toCalculate.charAt(i) == '*' || toCalculate.charAt(i) == '÷' ) {
operator_count++; /*Calculating
number of operators in a String toCalculate
*/
operators.add(toCalculate.charAt(i)); /* Adding that operator to
ArrayList*/
}
}
System.out.println("");
System.out.println("Return Value :" );
String[] retval = toCalculate.split("\\+|\\-|\\*|\\÷", operator_count + 1);
int num1 = Integer.parseInt(retval[0]);
int num2 = 0;
int j = 0;
for (int i = 1; i < retval.length; i++) {
num2 = Integer.parseInt(retval[i]);
char operator = operators.get(j);
if (operator == '+') {
num1 = num1 + num2;
}else if(operator == '-'){
num1 = num1 - num2;
}else if(operator == '÷'){
num1 = num1 / num2;
}else{
num1 = num1 * num2;
}
j++;
}
System.out.println(num1); // Prints the result value
}
}
****问题是我需要根据数学中的运算顺序(如乘法和除法)进行计算,而不是加法和减法 . 我该如何解决这个问题? ****
我已经使用String split()方法在运算符"+-/*"出现的任何地方分离String . 我使用了字符ArrayList来添加运算符 . 比在代码的最后部分我循环 splitted array of Strings 并且我通过将它解析为Integer来初始化int num1并使用splitted数组字符串的第一个值 . 和int num2与第二个值和使用运算符arraylist在它们之间执行计算(无论arraylist的索引处的运算符) . 并将结果存储在int num1中,反之亦然,直到字符串数组结束 .
[P.S] I tried to use Collection.sort but it sorts the above arraylist of operators in that order [*, +, -, /]. It puts division at the end while it should put division after or before multiplication symbol
1 回答
如果你想用大致相同的代码结构来完成它,而不是先把它变成反向波兰表示法,你可以尝试一种以反向优先顺序处理操作的方法 .
假设您有
*
和/
作为最高优先级,并且您将它们视为相同的优先级,因此从左到右处理;和+
和-
相同;那你会的首先在
+
和-
上拆分 .评估由
+
和-
分隔的零件,但现在按从左到右的顺序处理*
和/
.将
+
和-
应用于这些评估的零件 .因此,如果您的表达式是
3*4+5-6/2
,那么您的代码将首先拆分为现在评估这些子表达式
现在从左到右处理以评估最终答案
更一般地说,您通过表达式所需的通过次数取决于您拥有的优先级数;并且您需要处理从最低到最高的优先级 . 拆分表达;递归地评估仅考虑下一个优先级和更高级别的子表达式;结合起来得到最终答案 .
这将是一个不错的小Java 8流练习!