I am working on the Add em up project in the Blue Pelican Book. I would apreciate some help on figuring out how to get it to do subtraction to get the sum of 1249. Here is my code so far:

`import java.io.*;`
`import java.util.*;`
`public class AddEmUp
`{
 `public static void main(String args[])
 `{
 ` String s = "8 + 33 + 1345 - 137";
 ` Scanner sc1=new Scanner(s);
 ` sc1.useDelimiter(" +");
 ` String plusMinus=sc1.next();
  `int sum=Integer.parseInt(plusMinus);
  `while (sc1.hasNext())
` {
 ` String sign = sc1.next();
 ` if ( sign.contains("+"))
` {
 ` sum += Integer.parseInt(sc1.next());
` }
`}
`    System.out.println("Sum is: "+sum);
` }
`}

On line 15 you test for a sign of "+" and if you find it, you add the next number using += on line 17.
Testing for "-" and subtracting is exactly the same, except that it has "-" instead of "+" and -= instead of +=

I will do it in different way, use split(" ") method to split the input in array so you get something like this {"8","+","33","+","1345","-","137"} then u can use "switch" with "for" and say someting like this:
case number:
case "-" do...
case "+" do...
case "/" do...
etc...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.