gpt4 book ai didi

Java 数字在我的 addMinus 方法中没有加/减

转载 作者:行者123 更新时间:2023-12-02 08:50:53 30 4
gpt4 key购买 nike

我目前正在创建一个计算器,我正在其中读取 String 中的代码。并将操作数和运算符添加到 ArrayList 中。由于某种原因,系统没有执行我的 addMinus 中的操作方法。似乎 if-then 语句没有被执行。我不明白这是为什么。请帮忙。

    int counter = 0; //placeholder for the operators
//this searches to see if there is an operator
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '+' || c == '-') {
operator[counter] = Character.toString(c);
counter++;
}
}
addMinus(delimiter, operator, counter);
return null;
}


//Multiplies the numbers
public static String[] multDiv(String[] equation) {
for (int y = 0; y < equation.length; y++) {//iterates through elements in delimiter
for (int i = 0; i < equation[y].length(); i++) {//iterates through chars in element string
if (equation[y].charAt(i) == '*') {
String[] nums = equation[y].split("\\*");
equation[y] = String.valueOf(Double.parseDouble(nums[0]) * Double.parseDouble(nums[1]));
} else if (equation[y].charAt(i) == '/') {
String[] nums = equation[y].split("/");
equation[y] = String.valueOf(Double.parseDouble(nums[0]) / Double.parseDouble(nums[1]));
}
}
}
return equation;
}


/////*****SEARCHES FOR ADDS OR SUBTRACTS THE NUMBERS *****////
public static String[] addMinus(String[] numbers, String[] symbols, int counter) {
String[] equation = arrayMaker(numbers, symbols, counter);
Double answ = Double.parseDouble(numbers[0]);
int x = 0;

for (int i = 0; i < symbols.length; i++) {
if (symbols[i] == "- ") {
answ = -Double.parseDouble(equation[x + 1]);
System.out.println(" " + answ);
} else if (symbols[i] == "+ ") {
System.out.println(symbols[0]);
answ = +Double.parseDouble(numbers[x + 1]);
System.out.println(" " + answ);
}
x = +2;
}
System.out.println(answ);
return null;
}

最佳答案

注意这行代码:

if (symbols[i] == "- ")

您在这里比较的是引用,而不是值。您需要使用equals()方法。与 else if 的情况相同。引号之间有额外的空格怎么办?

关于Java 数字在我的 addMinus 方法中没有加/减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60780622/

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