String playerlist;
for(Player p : allplayers){
playerlist += p.getDisplayName() + ", ";
}
sendMessage(playerlist);
How can I accomplish this? I need to have a variable inside my for-loop, and then access it outside of the loop.
Thanks, and sorry if this is a very nooby question. I just can’t figure it out.
You’re close. You need to change the first line to
In Java it’s illegal to use a variable before it’s initialized, and the line
desugars(*) to
Once you initialize
playerlist, you are able to read off its contents into the temporary variable, and then updateplayerlist.There are two higher-level suggestions, though.
EDIT: As @edalorzo rightly mentions in the comments, you will only get an error for not initializing a local variable, and both static and instance fields are automatically initialized. Specifically, numeric types (
int,long,double, etc.) are initialized to 0, booleans are initialized tofalse, and reference types are initialized tonull.The spec explicitly describes the automatic initialization of fields, so you can rely on it, but it’s rarely what you want. Normally, you will want a non-default value of the field when you use it later, since
nullisn’t terribly useful (and many languages, particularly functional languages like Standard ML, go withoutnullaltogether). So I would recommend initializing all the fields of your objects in the constructor.(*): The “desugaring” I show above is almost accurate: in truth,
playerlistis evaluated only once, which doesn’t affect the behavior of this particular program.