Results 1 to 13 of 13
  1. #1
    weezer562 is offline Member
    Join Date
    Oct 2010
    Posts
    5
    Rep Power
    0

    Default Simple string add or subtract using scanner

    ok I managed to get this working correctly. The code is to take in a string such as "345 + 456 + 5654 + 3434" and add the numbers, this seems to be working. However what I am trying to change it to also allow subtraction including checking the first number for a + or - sign. I have tried many things but I guess I am not seeing how to set the If statement for that seems to be what would work. NOt sure how to check for - or + using the scanner. Any help would be great. I have tried placing an if statement within the while look to check if the scanner is at a + or - but I apparently am not using the correct condition.

    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 + 1345 +137 : ");
           String s = kb.nextLine( ); 
           Scanner sc = new Scanner(s);
           
           sc.useDelimiter("\\s*\\+\\s*"); 
                         //sc.useDelimiter("\\s*\\-\\s*"); tried for subtraction
           int sum = 0;
           
           while(sc.hasNextInt( ))
           {
                
                    sum = sum + sc.nextInt( );
              
           }
           
          
           System.out.println("Sum is: " + sum);
       }
    }

  2. #2
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Do you have to check a string such as "1 + 2 + 3", or is "1+2+3" (no spaces) also valid? Because if spaces are required, you could tokenize the string using spaces and parse each token, as there would be no space between the - and the number.

    If you want to get any more complex this gets really deep as you're getting into the area of lexical parsing... which can be quite painful.

  3. #3
    weezer562 is offline Member
    Join Date
    Oct 2010
    Posts
    5
    Rep Power
    0

    Default well

    it can have spaces I was able to get this to add and works fine but my main issues is adapting it to also check for subtraction including check the first number for a "-" . I have tried if statements and I just can not seem to work it out its a beginning java course nothing too difficult I am sure just not seeing it.

  4. #4
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by weezer562 View Post
    it can have spaces
    Can, or must?

    Quote Originally Posted by weezer562 View Post
    I was able to get this to add and works fine but my main issues is adapting it to also check for subtraction including check the first number for a "-" .
    I realize that; the problem is differentiating between -258 and 1-258. Which is why I ask about the spaces.

  5. #5
    weezer562 is offline Member
    Join Date
    Oct 2010
    Posts
    5
    Rep Power
    0

    Default

    Quote Originally Posted by Zack View Post
    Can, or must?


    I realize that; the problem is differentiating between -258 and 1-258. Which is why I ask about the spaces.
    Expected output would be something like this:

    Enter something like 8 + 33 + 1,345 -137 : 8 + 33+ 1345 -137
    Sum is: 1249

    I do understand what you are speaking of but I guess my confusion is what is keeping me from getting to the answer.

  6. #6
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Well, to allow for subtraction, you can change the pattern to recognize either + or -. Have you used regex before? You can use something like [+-] to represent either + or -.

    Unfortunately though, this doesn't solve the problem of the minus in front of a number.. but let's make sure you can get + and - down first.

  7. #7
    weezer562 is offline Member
    Join Date
    Oct 2010
    Posts
    5
    Rep Power
    0

    Default ...

    no have not used regx yet. Trying to figure out how to check for + and - using a dimilutive. Then from there doing the appropriate opperation was my thinking.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You could make your regex as complicated as you'd want....
    For instance this little puppy will separate all numbers from non-numbers:
    Java Code:
       public static void main(String[] args) {
          String data = "8 + 33 + -1345 +137- 232 -11";
          Scanner scanner = new Scanner(data);
                
          String delimiter = "((?<=\\d+)\\s*(?=\\D+))|((?<=\\D+)\\s*(?=\\d+))";
          scanner.useDelimiter(delimiter);
          
          while (scanner.hasNext()) {
             System.out.println("\"" + scanner.next() + "\"");
          }
          
       }
    Note I'm no regex expert, and I'm sure that you won't be able to use this in your assignment.

    My recommendation: force the user to put spaces between numbers and operators, and then split the String on space, or scan it with a Scanner using a standard delimiter, and then check if each token is a number or operator and act accordingly with it. Keep it simple.
    Last edited by Fubarable; 10-20-2010 at 04:35 AM.

  9. #9
    weezer562 is offline Member
    Join Date
    Oct 2010
    Posts
    5
    Rep Power
    0

    Default ok

    So I asked about the spaces and he said should be able to have none or more hence why the delimiter finds the + and any amount of white space around it. Tried working it out and unsuccessful. Any further help would be greatly appreciated. Thank you in advanced.

  10. #10
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Alright, I spent some time on pencil-and-paper and got an idea.

    1) You want to remove all spaces from the equation. So, "7 + -3" becomes "7+-3".
    2) You want to replace all "--" with "+" and all "+-" with "-" (basic arithmetic; I'm sure you understand this).
    3) Tokenize the string with + as the delimiter. (This is token array A)
    4) Loop through the tokens, and tokenize each one with - as the delimiter. (Token array A[B])
    5) For each element in A[B], subtract them.
    6) Once step 5 is done, A will contain only numbers. Now sum these.

    So it will look something like this:
    Java Code:
    8 + 7 - 3 + -3 - -8
    8+7-3+-3--8
    8+7-3-3+8
    
    A: ["8","7-3-3","8"] (tokenize)
    A: [["8"],["7","3","3"],["8"]] (separate into tokens)
    A: [["8"],["1"],["8"]] (complete subtraction of inner elements)
    A: [8,1,8] (now, sum these)
    A: 17 (done!)
    Hopefully that helps you. I know this is a bit complex but it's the simplest answer I could come up with.

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Zack View Post
    Alright, I spent some time on pencil-and-paper and got an idea.
    Why not read the "Dragon Book" by Aho, Sethi and Ullman? Even operator precedence parsing can do better than any home brew idea (and it allows for parentheses and double monary minus signs too ;-)

    kind regards,

    Jos
    Last edited by JosAH; 10-21-2010 at 07:39 PM.

  12. #12
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    I actually just wrote a lexical operator-precedence parser in Python. The point I'm making is that the OP is obviously only doing + and -, which means he's probably not in advanced programming yet. There's no reason to get into advanced whitepapers and such here as he doesn't need that level of complexity.

    Incidentally, this code does allow for double unary minus signs--if you repeat the replacement code. If you have:
    5+---8
    Then it will replace the +- with -, then the -- with +, then the +- with -, and you're left with 5-8. ;)

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Zack View Post
    I actually just wrote a lexical operator-precedence parser in Python. The point I'm making is that the OP is obviously only doing + and -, which means he's probably not in advanced programming yet. There's no reason to get into advanced whitepapers and such here as he doesn't need that level of complexity.
    I don't see the complexity in operator precedence parsing or even simple recursice descent parsing of expressions ...

    Quote Originally Posted by Zack View Post
    Incidentally, this code does allow for double unary minus signs--if you repeat the replacement code.
    Pay attention to the if part; I didn't even mention monary plus signs yet and your 'trick' costs quite a bit of time compared to, say, LL(1) parsing. In short: every home brew parsing method is worse than anything else backed up by at least a little theory. We're not living in the 1960s anymore when ALGOL/60 was considered a miracle.

    kind regards,

    Jos

Similar Threads

  1. Can i use Java Scanner with String?
    By guitar-maniac in forum New To Java
    Replies: 7
    Last Post: 09-15-2014, 08:59 AM
  2. Scanner Issues (User Input: Very Simple)
    By carlodelmundo in forum New To Java
    Replies: 8
    Last Post: 10-31-2008, 03:44 AM
  3. Area Subtract
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-23-2008, 12:07 AM
  4. Replies: 2
    Last Post: 06-02-2008, 11:24 PM
  5. Replies: 0
    Last Post: 11-20-2007, 05:59 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
  •