0

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);
` }
`}
3
Contributors
2
Replies
19
Views
3 Years
Discussion Span
Last Post by milil
0

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 +=

1

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...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.