java.util.regex.PatternSyntaxException: 在索引 0 + 附近悬空元字符 '+'

2022-08-31 19:45:11

当我启动我的UI时,我收到错误,导致此代码在标题中向我吐出错误。它适用于我的所有其他运算符符号,所以我真的不确定这里发生了什么。我不想发布所有的代码,所以你可以找到其余的,如果这还不够在我的gitHub上:https://github.com/jparr721/Calculator-App/tree/master/src/calculator

public class Calculation_Controls {

    public double A, B;

    private String[] operators = new String[] {"-","+","/","*","x","^","X"};


    /**
     * Check for the symbol being used within the TextArea to then
     * apply the correct caculation method.
     * FIXME - Allow for multiple symbols to be used and have them return
     * FIXME - a result in accordance with PEMDAS
     *
     *@param nums
     *
     * @return operator, or error
     */
    public String findSymbol(String nums) {

        for (String operator : operators) {
            if (nums.contains(operator)) {
                return operator;
            }
        }
        return "invalid input";
    }

    /**
     * Input method to take the user input from the text area
     * and apply the correct calculation to it
     *
     * @param nums - Stores the input as a String which I then convert to an int
     *             then back to a string to be printed to the TextArea
     *
     * @return - The result of the calculation as a string
     */
    public String input(String nums){

        String operator = findSymbol(nums);
        if (operator == null){
            System.out.println("Invalid input");

        }
        String[] split = nums.split(operator);
        int left = Integer.parseInt(split[0]);
        int right = Integer.parseInt((split[1]));
        String result = "";

        switch (operator){

            case "+":
                result = Double.toString(add(left, right));
                break;
            case "-":
                result = Double.toString(subtract(left, right));
                break;
            case "*":
            case "x":
            case "X":
                result = Double.toString(multiply(left, right));
                break;
            case "/":
                result =  Double.toString(divide(left, right));
                break;
            case "^":
                result =  Double.toString(pwr(left, right));
                break;
            default:
                System.out.println("Invalid Operator");
        }
        return result;
    }

答案 1

正则表达式中有保留字符,您应该对这些字符进行移植以实现所需的内容。例如,你不能使用,你必须使用。String.split("+")String.split("\\+")

正确的运算符是:

String[] operators = new String[] {"-","\\+","/","\\*","x","\\^","X"};

答案 2

在您的情况下,并被视为具有特殊含义,通常称为元字符。 方法采用正则表达式作为其参数并返回数组。为了避免将上述内容视为元字符,您需要在代码中使用这些转义序列+*^String.split()String"\\+" "\\*" "\\^"

像这样修改运算符数组

private String[] operators = new String[] {"-","\\+","/","\\*","x","\\^","X"};

有关更多 detalis refere 这些链接正则表达式.Pattern and String.split()