title: Blue Pelican Java Textbook Lesson 17 Project AddEmUp
body: <p>So my teacher gave me an assignment to do (will be shown below) and I tried to do it but just could not figure it out, here's the assignment:</p>
  
  <p>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 white space) as delimiters and produces the sum of these numbers (1523).</p>
  
  <pre><code>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); 
  
  
  
   } 
  
  }
  </code></pre>
  
  <p>Now modify the program as to allow either plus or minus signs</p>
  
  <p>^^^THAT WAS THE ASSIGNMENT^^^</p>
  
  <p>Here is my source code:</p>
  
  <pre><code>//I can't get it to work if I use subtraction and addition at the same time but they work separately
  
  import java.util.Scanner;
  
  public class AddEmUp {
  
      public static void main(String[] args) {
  
          //Here we create a String
          Scanner kb = new Scanner(System.in);
          System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
          String s = kb.nextLine();
  
          //Now we convert the String to a scanner because we will be using Scanner methods
          Scanner sc = new Scanner(s);
  
          //Creates sum
          int sum = 0;
  
          //Does it's magic if it is addition
          if (s.contains("+")) {
              sc.useDelimiter("\\s*\\+\\s*");
              while (sc.hasNextInt()) {
                  sum = sum + sc.nextInt();
              }
          }
  
          //Does it's magic if it is subtraction
          if (s.contains("-")) {
              sc.useDelimiter("\\s*\\-\\s*");
              while (sc.hasNextInt()) {
                  sum = sc.nextInt();
                  sum = sum - sc.nextInt();
              }
          }
  
          //Prints the magic
          System.out.println("Sum is: " + sum);
      }
  }
  </code></pre>
  
  <p>Can anybody help me solve the problem (First comment in my source code)???</p>