How to evaluate math expression with only + and - operations in string with Java

1 Answer

0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        String expr = "1 + 4 + 5 - 7 + 9";
        
        String[] arr = expr.replaceAll("\\s", "").split("\\+|(?=-)");
        
        int result = Arrays.stream(arr).mapToInt(Integer::parseInt).sum();
        
        for (String s : arr) {
            System.out.println(s);
        }

        System.out.println("result = " + result);
    }
}




/*
run:

1
4
5
-7
9
result = 12

*/

 



answered Jun 7, 2021 by avibootz

Related questions

1 answer 169 views
1 answer 113 views
1 answer 117 views
1 answer 99 views
...