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);
}
}
Just put
+
,-
inside a character class.