Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Creating Strings from while loop (Java)

Options
  • 28-11-2011 6:10pm
    #1
    Registered Users Posts: 839 ✭✭✭


    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 Posts: 11,979 ✭✭✭✭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 Posts: 68,317 ✭✭✭✭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 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