Results 1 to 4 of 4
  1. #1
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    265
    Rep Power
    6

    Default Multiples Integers from a String

    I'm working on an interesting project that requires the user to input psuedo-java commands into the console, and things happen according to what they enter. However, I'm having a bit of trouble getting the parameters out of the input String.

    Say I have this input:

    command(1, 2, 3, 4)

    I need to get "command", which is easy (String.startsWith("Command")).
    But, the 1, 2, 3, and 4 aren't so easy. How would I go about extracting these individual numbers from the String? I was hoping there was a String.nextInt() method, but I wasn't so lucky. :P

  2. #2
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    check out the "split" method of the string class, using the comma + qhitespace as your delimiter. of course, there will be some set up needed to get to that point as well.

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

    Default

    Hm, you could split the String using regex one way or another. I'm no regex expert, but this seems to work:
    Java Code:
        String commandStr = "command(1, 2, 3, 4)";
        String[] tokens = commandStr.split("[\\(\\)\\,]\\s*");
        for (String token : tokens)
        {
          System.out.println(token);
        }
    What I was trying to split on here was an open or closed parenthesis or a comma, this part: [\\(\\)\\,]
    optionally followed by whitespace of any length, this part: \\s*
    Last edited by Fubarable; 04-01-2009 at 12:55 AM.

  4. #4
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    265
    Rep Power
    6

    Default

    Hmm, thanks. I don't know much about this "regex," but I think I'm going to look into it. If that doesn't work out, I'll try the split stuff. Thanks. :)

Similar Threads

  1. Sorting 3 Integers Using If Else
    By MSteinman in forum New To Java
    Replies: 12
    Last Post: 02-19-2010, 01:52 PM
  2. how to get the Integers out of a String
    By JordashTalon in forum New To Java
    Replies: 10
    Last Post: 01-30-2009, 07:28 PM
  3. Replies: 1
    Last Post: 10-20-2008, 08:55 PM
  4. Finding Median of X Integers
    By Hasan in forum New To Java
    Replies: 3
    Last Post: 08-12-2008, 03:06 PM
  5. Random Integers
    By www.kwalski.com in forum Java Applets
    Replies: 8
    Last Post: 12-09-2007, 06:49 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
  •