Java get a group of user names
I've coded a program where there is like 5 people "killing" a monster, and i need a piece of code to get all of the me开发者_运维技巧mbers "nickname" (getName() ) and display them with a coma beetwen, how could I do that?
I guess I could do a for loop but ye, not sure how to add the comas beetwen then..
Assuming your players are in a collection, you can indeed use a loop, or you can use some 3rd party library, like guava:
Joiner.on(',').join(players);
Or commons-lang:
StringUtils.join(players, ',');
Well, what you do in your loop depends on the way you have this information stored and the structure you are using for things...
But an example would be:
String namesList = "";
for(int i = 0; i != 5; ++i){
String name = users[i].getName()
namesList += name;
namesList += ", ";
... //do something else
}
http://snippets.dzone.com/posts/show/91
Or if you can use Google Guava (highly recommended as a tool in your belt anyway):
String nickname = Joiner.on(",").join(listOfMembers);
精彩评论