gpt4 book ai didi

java - BODMAS系统的加减法

转载 作者:行者123 更新时间:2023-12-04 05:14:04 25 4
gpt4 key购买 nike

我一直在构建一个简单的公式计算器,并且一直在加减法中。正如您应该知道的,在计算方程时,您遵循优先级的算术规则,即括号、顺序:幂函数、除法、乘法、加法和减法。问题是加法和减法的优先级相同,因此您可以从左到右阅读。到目前为止,这是我的代码:

{
ArrayList<String> equation = java.util.Arrays.asList({"2","-","2","+","5"});

while(equation.contains("+")){
addMe(equation);
}
while(equation.contains("-")){
minusMe(equation);
}
}

public static void addMe(ArrayList<String> numberList){
for (int i = 0, n = numberList.size(); i < n; i++) {
String value = (String) numberList.get(i);
if(value.equals("+")){

String wordBefore = (String) numberList.get(i-1);
String wordAfter = (String) numberList.get(i+1);
System.out.println("This is the word before " + wordBefore);
System.out.println("This is the word after " + wordAfter);
double doubleFromBefore = Double.parseDouble(wordBefore);
double doubleFromAfter = Double.parseDouble(wordAfter);
double answer = doubleFromBefore + doubleFromAfter;
System.out.println("This is the answer: " + answer);
String stringAnswer = String.valueOf(answer);
String newNum2 = value.replace(value, stringAnswer);
numberList.set(i,newNum2);
numberList.remove(i-1);
numberList.remove(i);
break;
}
}
}

minusMe 方法与 addMe 方法完全相同,只是在相关地方加了“-”。我遇到的问题是让方程一次从左到右读取一项,然后执行加法或减法。理想情况下,我认为我需要将我的 2 while 循环与迭代器结合起来,以解决问题,但我的尝试没有奏效。知道这是否会解决我的问题吗?如果是这样,请提供修改后的循环。

问候

最佳答案

看看这个

java.uti.ArrayList<String> equation = java.util.Arrays.asList({"2","-","2","+","5"});
java.util.Iterator<String> equIterator = equation.iterator();
int result = 0;
int multiplier = 1;
while(equIterator.hasNext()){
String operandOrOperator = equIterator.next();
if(operandOrOperator.equals("+")){
multiplier=1;
}else if(operandOrOperator.equals("-")){
multiplier=-1;
}else if(operandOrOperator.equals("*")){
result*=Integer.parseInt(equIterator.next()); // Assuming that next element will be there always after operator.
}else{
result+=(multiplier * Integer.parseInt(operandOrOperator));
}
}
System.out.println("Final result : " + result);

关于java - BODMAS系统的加减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14517390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com