I've been working on the Blue Pelican Java project called Add 'Em Up for several hours now, and I can't figure out how to get it to work. The project description is this:
Consider the following program that allows something like 8 + 33 + 1,345 +137 to be entered as String input from the keyboard. A Scanner object then uses the plus signs (and any adjoining whitespace) as delimiters and produces the sum of these numbers(1523).
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( );
Scanner sc = new Scanner(s);
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}
The output will typically look like this: Enter something like 8 + 33 + 1,345 +137 : 8 + 33 + 1,345 + 137 Sum is: 1523 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 : 8 + 33+ 1,345 -137 Sum is: 1249
The code below is what I currently have. The program works just fine for adding numbers, but for some reason the subtraction isn't working. For example, if you enter 5-2, the answer comes out as -7 instead of 3.
public class AddEmUp {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
int sum = 0;
if (s.contains("+")) {
sc.useDelimiter("\\s*\\+\\s*");
while (sc.hasNextInt()) {
sum = sum + sc.nextInt();
}
}
if (s.contains("-")) {
sc.useDelimiter("\\s*\\-\\s*");
while (sc.hasNextInt()) {
sum = sum - sc.nextInt();
}
}
System.out.println("Sum is: " + sum);
}
Any help on what I should be trying to do in order to fix this would be much appreciated. Thanks!