Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Creating Strings from while loop (Java)

  • 28-11-2011 06:10PM
    #1
    Registered Users, Registered Users 2 Posts: 867 ✭✭✭


    I'm trying to create a range of Strings, the names depending on an integer. Something like this........

    int i=1;
    while (i<11)
    {
    String Valuei = "text"+i;

    i++;
    }

    So that I end up with 10 strings- Value1=text1, Value2=text2 and so on

    But the syntax that I've mentioned "String Valuei = "text"+i;" is obviously made up - I'm looking for the correct way to implement this. Can't find anything obvious so far.
    Any of you done this before?

    Thanks in advance


Comments

  • Registered Users, Registered Users 2 Posts: 12,026 ✭✭✭✭Giblet


    You need either an array or a dictionary / hashmap of some sort.
    String myStrings = new String[10];
    
    for(int i = 0; i < myStrings.length; i++){
       myStrings[i] = "text" + i;
    }
    
    If you need a key-value pair for some reason (which i doubt, you prob just want 10 strings stored somewhere with dynamic values), you could use a HashMap (I haven't used java in years so might be slightly outdated here)
    HashMap hash = new HashMap();
    for(int i = 0; i < 10; i++){
      hash.put("Value" +i, "Text" +i);
    }
    
    hash.get("Value1"); // should equal "Text1"
    
    


  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    You want to create an array of strings.

    Having variables with variable names is problematic and painful.

    Better off saying
    int i=1;
    String[] value = new String[10];
    while (i<11)
    {
    	value[i-1] = "text"+i;
    	i++;
    }
    
    I think that's the Java syntax anyway.

    If you don't know what an array is or you've never seen "String[]" before, a quick google should reveal all.


  • Registered Users, Registered Users 2 Posts: 3,945 ✭✭✭Anima


    Use String.Format maybe.

    [PHP]
    int i = 1;
    Vector<String> myStrings = new Vector<String>();

    while (i < 11)
    {
    myString.add( String.Format ("text %d", i++) );
    }
    [/PHP]

    If you don't know what vector is, its just a dynamic array. The main thing is that String.Format will create a new String when you call it. Some of the syntax might be wrong, I haven't used Java since a few years.


Advertisement