#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0

    Spliting a String and holding variables


    Hello guys, I am making a simple Mastermind game, which is going to be played in the console. My task includes starting the game with entering sth like this: "start 4 5 34356". Where start initializes the game, 4 is the number of possible tries to guess, 5 is for the length of the code to be guessed and 34356 is the code itself. The problem is that I have no idea how to write all those things and match every token with its variable. I really need help, because it must be done soon and I am a little bit stuck.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2009
    Location
    London, ON
    Posts
    322
    Rep Power
    215
    Check out the String API and look at the "Split" method.

    It's invoked similarly to this:
    Code:
    String sInput = "start 4 5 34356";
    String[] sArr = sInput.split("DELIMITER");
    Where DELIMITER would be a space in your case (Your input is space-delimited).

    This will create an array of String objects that would look something like this:

    [start] [4] [5] [34356]

    That should get you started. Please let us know if you have more questions.
    <Tetrad> the program I just wrote 1) compiled the first time without any errors and 2) worked like it was supposed to
    <Tetrad> I don't know whether to be proud or scared to death
    Originally Posted by DaWei_M
    That covers a multitude of your sins, right there.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0
    Okay, but then how do I hold the different values in variables ?
  6. #4
  7. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,724
    Rep Power
    348
    The split() method puts the separate parts of the String into an array.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2005
    Posts
    74
    Rep Power
    33
    Look over the reference material (API docs) for Arrays... but for example:

    Code:
    String initialisation = yourArray[0];
    String possibleTries = yourArray[1];
    String codeLength = yourArray[2];
    String code = yourArray[3];
    Of course, you'll have to do all the usual safety checks to ensure you have all the required element in the input string, otherwise you could get an Out of Bounds Exception (looking for something which isn't there).

IMN logo majestic logo threadwatch logo seochat tools logo