Search code examples
javastringbuffer

Adding a Java Strings and convert it into integer and get its sum


I would like to need you're help for this. I need to get the total of the said equation and I'm stuck to the concatenation process which will let me add the result of the equation.

String eq = "15+5cdf-45+90$%#@";
StringBuffer s = new StringBuffer(eq);

for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) >= 48 && s.charAt(i) <= 57 || s.charAt(i) == '+' || s.charAt(i) == '-') {

    } else {
        s.deleteCharAt(i);
        i--;
    }

}

System.out.println(s);  

String a = new String (s);

//15+5-45+90

String y = "";
String z = "";  

for (int x = 0; x < a.length(); ++x) {

    if (a.charAt(x) == '+'){
        a = a.substring(0, x);
        y = a;
    } 

    z = y.concat(y);
}

System.out.println(z);

Solution

  • You don't need to be doing most of what you are doing.

    public static void main(String[] args) {
        String eq = "15+5cdf-45+90$%#@";
        long sum = eval(eq);
        System.out.println("sum: " + sum);
    }
    
    private static long eval(String eq) {
        int sign = +1;
        long num = 0, sum = 0;
        for (int i = 0; i < eq.length(); i++) {
            char ch = eq.charAt(i);
            if (ch >= '0' && ch <= '9') {
                num = num * 10 + ch - '0';
            } else if (ch == '-' || ch == '+') {
                sum += sign * num;
                sign = ch == '-' ? -1 : +1;
                num = 0;
            }
        }
        sum += sign * num;
        return sum;
    }
    

    prints

    65
    

    As you can see all you need as a parser which evaluates the expression which ignores unexpected characters.

    Note: the eval creates no objects.