
String Method problem.
Hey guys, I am new to Java and I need some help trying to solve this problem.
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");
String s = kb.nextLine( ); //Best to store in a String and then create a new Scanner
//object; otherwise, it can get stuck waiting for input.
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}
I have been stuck at trying to solve this problem:
"Now modify this program so as to allow either plus or minus signs. Don’t forget to allow for a
leading plus or minus sign on the first number in the sequence. If the leading number has no sign,
assume the number is positive. Your output should typically appear as follows:
Enter something like 8 + 33 + 1,345 137
Sum is: 1249"
Can you please also explain abit about how these delimiters work?
Thanks!