Reputation: 3
i've just recently started with java on my school, and i have a bit of a problem. Well not really a problem, since i've found a way to solve it (complicated one though).
im supposed to make a poemgenerator.
so, in a for loop, i want to build a string, of words that is in some arrayLists, so im using a StringBuilder for that.
the thing is, that my sentence should consists of words from 4 different arrayLists, (different wordclasses)
and, a while ago, i programmed in actionscript3, and there was something there that i could really use for this problem, that would make the code so much simplier. using This[]
so. i have 4 lists: list0, list1, list2, list3
and in my loop, i would've done something like the following in AS3(flash, actionscript3)
for(int i = 0; i<4; i++){
poem.append(This["list" + i].get(randomindex))
}
so that the first time the loop goes, i get a random word from list0, the second time, i get a random word from list1, and so on... is there any way to do this simple in java? x)
Upvotes: 0
Views: 138
Reputation: 20544
You can use array;
List<String> list1 = Arrays.asList("String1", "String2");
List<String> list2 = Arrays.asList("String3", "String4");
List<String> list3 = Arrays.asList("String5", "String6");
List<String> list3 = Arrays.asList("String7", "String8");
List<String>[] lists = new List[]{ list1, list2, list3, list4};
Then replace your code with
for(int i = 0; i<4; i++){
poem.append(lists[i].get(randomindex));
}
Upvotes: 3
Reputation: 195209
Make a fullList : List<List<String>>
contains your list0-3
Random r = new Random();
StringBuildr poem = new StringBuilder();
for (List<String> list : fullList)
poem.append(list.get(r.nextInt(list.size())));
poem.toString(); //this is your poem
codes are not written in IDE, not tested either.
Upvotes: 1