Page 1 of 2 12 LastLast
Results 1 to 20 of 25
  1. #1
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Help with Delimiters/While loops

    * This is project 17 and it asks to create a code that uses delimiters/while loops to add or subtract numbers, but I have no idea how to code that! I used the s.contains("-") and s.contains("+") in two if statements with while loops in them, but it wouldn't work. Please tell me the best way to code where an addition and subtraction sign will work! Please get me to the right direction!
    * I really, really apologizing for not specifying the title of what I needed help with! I'll make sure to do so in the future!!
    Project… Add ‘em Up
    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).
    Java 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);
    }
    }
    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
    By, "wouldn't work" I meant to say that the program prints out a negative number(sorry). My code is here below:
    Java 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.
    boolean sa = s.contains("-");
    sc.useDelimiter("\\s*\\+\\s*");
    int sum = 0;
    while(sc.hasNextInt( ))
    {
    if(sa == true)
    {
    sc.useDelimiter("\\s*\\-\\s*");
    sum = sum - sc.nextInt( ); 
    }
    else 
    {
    sum = sum + sc.nextInt( );
    }
    
    }
    System.out.println("Sum is: " + sum);
    }
    }
    It prints -8 :/
    Last edited by bubblegum; 09-06-2012 at 12:41 AM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    Please edit the post and wrap the code in code tags. See: BB Code List - Java Programming Forum

    it wouldn't work.
    Please explain what "wouldn't work" means. Did you get errors or did the program give wrong results.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    I've re-edited it Norm, I hope I explicated a little further.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    Why do all the statements start in the first column? Statements should be indented 3-4 spaces to show their nesting logic level within if statements and methods.

    Can you copy the console's contents that shows the input and output from when the program is executed?

    With windows: To copy the contents of the command prompt window:
    Click on Icon in upper left corner
    Select Edit
    Select 'Select All' - The selection will show
    Click in upper left again
    Select Edit and click 'Copy'

    Paste here.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    I was only taught how to use the bluej complier so Norm can I paste the results from the console?

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    Sorry, I don't know anything about bluej. It's hard to understand the problem without seeing the console from when the program executes.

    The posted code still needs formatting.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    Ok I'll reedit code with indents and post bluej's console results.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,953
    Rep Power
    19

    Default Re: Help with Delimiters/While loops

    You need to give us the output for a run, as we have no idea (at least from reading the OP) what values you put in to get -8 out.

    Also you really need to indent your code...
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default Re: Help with Delimiters/While loops

    You need to rethink your algorithm.

    If the equation contains a '-' you set a flag to true. Then if that flag is true you subtract the next int from the sum. It will subtract ALL ints and not just the one preceded by a '-'. If input is 8-3 then the result will be -11 (0 - 8 - 3). Since you only get -8 I'm assuming the call to hasNextInt fails and only the 8 is subtracted.

  10. #10
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    Ok here is the code (reindented)
    Java 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.
    boolean sa = s.contains("-");
    sc.useDelimiter("\\s*\\+\\s*");
    int sum = 0;
    
    
                   while(sc.hasNextInt( ))
    {
    
    
    
       if(sa == true)
    {
       sc.useDelimiter("\\s*\\-\\s*");
       sum = sum - sc.nextInt( ); 
    }
    
    
      else
    {
        sum = sum + sc.nextInt( );
    }
     
    
    }
                System.out.println("Sum is: " + sum)
    }
    
    
    
    }
    Output is in the screenshot
    Help with Delimiters/While loops-projectaddemup.png

  11. #11
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    Quote Originally Posted by Junky View Post
    You need to rethink your algorithm.

    If the equation contains a '-' you set a flag to true. Then if that flag is true you subtract the next int from the sum. It will subtract ALL ints and not just the one preceded by a '-'. If input is 8-3 then the result will be -11 (0 - 8 - 3). Since you only get -8 I'm assuming the call to hasNextInt fails and only the 8 is subtracted.
    Ok that makes sense, but how would I set the program to switch between each easily? a nested if statement? Store the ones with positives in front in one variable, and store the ones with negatives in front with another variable and add them together? I don't understand how to get to the point where it can accept +'s and -'s.

  12. #12
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    Ok I have somewhat good news! I've been able to recode where it adds or subtracts...but it still can't do both! Is there anyway you could tweak this so that it could?
    Java Code:
    public class Modded
    {
       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);
           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=sc.nextInt()-sc.nextInt();
         }
         
        }
       
        System.out.println("Sum is: "+sum);
    
    }
    
    
    }
    This is what happens with just negatives (only 2 numbers work):
    Help with Delimiters/While loops-addemups.png
    With Positives (Positives allow more than 2):
    Help with Delimiters/While loops-addeeeeee.png
    And both(doesn't work)
    Help with Delimiters/While loops-efdfdfdffd.png
    Any suggestions would be awesome! :)

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    The contents of the images is too small to read. Can you copy the console contents and paste it here?

    Also add some comments to the console output explaining what the problem is and what you want the program to do differently.
    Last edited by Norm; 09-13-2012 at 02:52 AM.
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    1st Console:
    Enter something like 8 + 33 + 1345 - 137: 33 - 2
    Sum is: 31
    (It does that correctly)

    2nd
    Enter something like 8 + 33 + 1345 -137: 8 + 3 + 3
    Sum is: 14

    (That also is done correctly)

    3rd
    Enter something like 8 + 33 + 1345 -137: 8 + 3 -1
    Sum is: 8
    (The program should be able to ADD and SUBTRACT

    That's what I need it to do. It needs to allow for addition and subtraction to coexist in one problem, and it needs to let me regardless of the order(except for the leading number it is always positive)

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    needs to allow for addition and subtraction to coexist
    You need to redesign the logic for the problem.
    The posted code only works for simple input like: 2 + 3 and 4 - 5

    Before writing any more code, work on a design. Write the steps the code needs to do in pseudo code and post the steps here. We'll help you get a design that will work on longer strings of numbers with + and -
    When you have a design that works, then code it.
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    1. Enter an arithmetic expression that adds and subtracts numbers on the same line(leading number positive)
    2. An string.contains checks for a positive sign
    3. It adds up all the numbers until it hits a negative sign
    4. It switches to a "-" delimiter and subtracts from the sum
    5. It pulls out the sum
    6. The output of the sum is printed

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    For step 2, what if the first sign is a - and the last sign is a +. The String contains a + but there are -s before it. Step 2 does not work.
    How do steps 3 & 4 work? If there is a + first, when does the code see that there is now a -???

    Steps 2 & 3 need to be re-worked.

    What if there were a class with methods that would return the next tokens from the String one after the other. First a number then an operator (+ or -) then another number then another operator etc to the end of the String.
    If you don't understand my response, don't ignore it, ask a question.

  18. #18
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    I see what you mean, but I still don't understand..How would you make the program switch from addition to subtraction without doing only one? That's the only part I don't understand at all.

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default Re: Help with Delimiters/While loops

    Pseudo code:
    initialize total to value of first token (a number)
    begin loop continue until no more tokens
    get next token (an operator)
    get next token (a number)
    update total using operator and number
    end loop
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    bubblegum is offline Member
    Join Date
    Sep 2012
    Posts
    19
    Rep Power
    0

    Default Re: Help with Delimiters/While loops

    Norm, I still don't understand one thing: How do you switch between delimiters without it messing up?!

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 1
    Last Post: 03-25-2012, 02:40 AM
  2. Replies: 16
    Last Post: 01-31-2012, 08:36 PM
  3. Replies: 0
    Last Post: 08-07-2011, 08:32 PM
  4. Replies: 0
    Last Post: 02-21-2011, 11:50 AM
  5. Replies: 1
    Last Post: 04-26-2007, 03:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •