gpt4 book ai didi

java.util.regex.PatternSyntaxException : Dangling meta character '+' near index 0 +

转载 作者:搜寻专家 更新时间:2023-10-30 20:58:18 24 4
gpt4 key购买 nike

我在启动 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;
}

最佳答案

正则表达式中有保留字符,您应该对这些字符进行转义以实现您想要的效果。例如,你不能使用String.split("+"),你必须使用String.split("\\+")

正确的运算符是:

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

关于java.util.regex.PatternSyntaxException : Dangling meta character '+' near index 0 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40246231/

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