Java 字符串计算器,第一个数字是负数

Java string calculator, first number is negative

所以我有这段代码是我从另一个问题中得到的,但它从未回答过,如果 String a = "-5+20-15+8" 并且第一个数字为负数,我将如何更改代码,现在它给出了一个错误。

 String a = "5+20-15+8";
    System.out.println(a);
    String operators[]=a.split("[0-9]+");
    String operands[]=a.split("[+-]");
    int agregate = Integer.parseInt(operands[0]);
    for(int i=1;i<operands.length;i++){
        if(operators[i].equals("+"))
            agregate += Integer.parseInt(operands[i]);
        else 
            agregate -= Integer.parseInt(operands[i]);
    }
    System.out.println(agregate);

一个快速修复方法是确保在将字符串拆分为操作数时不在第一个 - 拆分。

String operands[]=a.split("(?<=\d)[+-]");

此正则表达式断言 +- 后必须跟一个数字。

这样,第一个操作数将是 -5,然后将被 Integer.parseInt 正确解析。

如果你只需要处理加法和减法,这里有另一种思考问题的方式:没有运算符,只有操作数。 -5+20-15+8中只有操作数-5+20-15+8,你只需要将它们全部相加即可。我们可以将字符串拆分为数字-[+-] 边界处的操作数:

String[] operands = a.split("(?<=\d)(?=[+-])");

然后将它们全部加起来:

int result = 0;
for (int i = 0 ; i < operands.length ; i++) {
    result += Integer.parseInt(operands[i]);
}
// or:
// int result = Arrays.stream(operands).mapToInt(Integer::parseInt).sum();
System.out.println(result);

问题是 -+ 用作分隔符,因此 -5 中的第一个 - 会被错误地解释为分隔符。快速解决方案是期望这两个运算符周围必须有空格,因此当它们代表符号时,它们将自己与情况区分开来。

public class Main {
     public static void main(String []args){
         String a = "-5 + 20 - 15 + 8";
            System.out.println(a);
            String operators[]=a.split("[0-9]+");
            String operands[]=a.split(" [+-] ");
            int agregate = Integer.parseInt(operands[0]);
            for(int i=1;i<operands.length;i++){
                if(operators[i].equals(" + "))
                    agregate += Integer.parseInt(operands[i]);
                else 
                    agregate -= Integer.parseInt(operands[i]);
            }
            System.out.println(agregate);
     }
}