Adding and Subtracting numbers from a String

1.2k views Asked by At

This program takes in a string and adds up all the integers in it, I have set the delimiter to be "+" surrounded by any amount of white space. It works fine with that but now I want it to work with any negative integers as well, for instance if I input "8 + 33 + 1,345 - 37"; the output is 41.It doesn't even get to 1,345 or subtracts -37 from the total. Are delimiters "skipped" ? For instance, would I be correct if I say the compiler goes to 8 and then '+' is skipped then it goes to 33? And if I set the delimiter to be "\s*\+|-\s*" (an attempt of + or -), the output is still 41, why?

import java.util.*; 

import java.io.*;

public class Add_em_up
  {

            public static void main (String args [])            

        {     

            Scanner x = new Scanner (System.in);


            System.out.print("Enter something like 8 + 33 + 1,345 + 137 :");


            String s = x.nextLine();

            Scanner sc1 = new Scanner (s);
            sc1.useDelimiter("\\s*\\+\\s*");                

            int sum = 0;
            while (sc1.hasNextInt())
            {
                sc1.skip(",*");
                if (sc1.hasNextInt())
                {
                    sum = sum + sc1.nextInt();                 
                }

            }
            System.out.println("Sum is: " + sum);
        }
  }
2

There are 2 answers

4
Avinash Raj On BEST ANSWER

Just put +, - inside a character class.

sc1.useDelimiter("\\s*[-+]\\s*");    
0
nomanr On

Okay here's an easy solution if you are interested in using the library Exp4j. Library will do all the calculation and all you've to do is pass the equation and get the result.

Here's an example.

Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
    .variables("x", "y")
    .build()
    .setVariable("x", 2.3)
    .setVariable("y", 3.14);
double result = e.evaluate();