Reputation: 13
I'm trying to append to a String
inside a for
loop. After it iterates I access the String
for use but it's still empty. Why is it still empty?
Code:
String message = "";
for(int i = 1; i==args.length; i+=1){
message+=" "+args[i];
}
I'm developing a plugin for Bukkit (and the args
are from Bukkit)
Upvotes: 1
Views: 43
Reputation: 201497
There are several options, first the second parameter in your for
loop should be something like
String message = "";
for(int i = 1; i < args.length; i+=1){
message+=" "+args[i];
}
But, arrays start at 0
and you can use ++
so I think you really wanted
String message = "";
for(int i = 0; i < args.length; i++){
message+=" "+args[i];
}
Then, you might prefer the simpler for-each
loop like
String message = "";
for(String arg : args){
message+=" "+arg;
}
Finally, I would really prefer you use a StringBuilder
(to avoid creating so many temporary String
s) like
StringBuilder sb = new StringBuilder();
for(String arg : args){
sb.append(" ").append(arg);
}
String message = sb.toString();
Upvotes: 2