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

标签 java arrays parsing methods calculator

我目前正在创建一个计算器,我正在其中读取 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/

相关文章:

java - 如何设置 netbeans 中的记录器将异常信息打印到文件?

java - OpenJDK 11.0.4 在类路径中有 java-atk-wrapper.jar

c++ - 不会在 'int*' 到 'int [0]' 的分配中编译不兼容的类型

javascript - 在javascript中使用另一个数组创建数组

python - 使用 BeautifulSoup4 和 Python 3 解析 html 表

c# - double.Parse 和 Double.Parse 有什么区别?

java - 使用 DOM 解析器 Java 解析具有嵌套重复元素名称的 xml 文档。

java.sql.SQLException : The Network Adapter could not establish the connection

java - 开发 Java Web 服务的最佳 IDE(适合初学者)

php - 为什么 array_filter 不工作?