【发布时间】:2016-04-26 14:02:52
【问题描述】:
我正在尝试用 Java 编写一个程序,它需要输入一个字符串值 像 s = "1+27-63*5/3+2" 并返回整数值的计算
下面是我的代码
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() 方法在出现运算符“+-/*”的地方分隔字符串。我已经使用字符 ArrayList 在其中添加运算符。 与代码的最后一部分相比,我在那个 拆分的字符串数组 中循环,并且通过将字符串拆分数组的第一个值解析为整数来初始化 int num1。和 int num2 与第二个值和使用运算符 arraylist 在它们之间执行计算(无论是 arraylist 索引处的运算符)。并将结果存储在 int num1 中,反之亦然,直到字符串数组的末尾。
[P.S] 我尝试使用 Collection.sort,但它按 [*、+、-、/] 的顺序对上述运算符数组列表进行排序。它将除法放在末尾,而应该将除法放在乘法符号之后或之前
【问题讨论】:
-
处理此问题的常用方法是将输入转换为前缀表示法并使用堆栈进行处理。 Here's a good example
-
你为什么认为 sort 在这里会有帮助? sort 的作用是根据某种顺序重新排列集合中项目的顺序 - 默认情况下,这只是字符串的字典顺序。
-
简单的方法是使用ScriptEngine : stackoverflow.com/questions/3422673/…
-
我真的不认为这种排序在这里会有所帮助。起初我只是想找到一种方法来实际如果java根据数学中的操作顺序对运算符进行排序。
-
"java 根据操作顺序对运算符进行排序"--没有内置帮助。您可以编写自己的方法来执行此操作,但上面介绍的想法是实现目标的更好方法。
标签: java string for-loop arraylist calculator