Reputation: 25
java noob here...
This is driving me nuts because I know it's something so simple but I have been working on this for 30 mins...
this is from codefights:
For arguments = ["Code", "Fight", "On", "!"] and separator = "/", the output should be myConcat(arguments, separator) = "Code/Fight/On/!/".
my code:
String myConcat(String[] arguments, String separator) {
for(int i = 0; i <= arguments.length; i++){
String output = arguments[0] + separator;
}
return output;
}
error: file.java on line 5: error: cannot find symbol return output; ^ symbol: variable output location: class _runfniek 1 error
any tips would be greatly appreciated...
Upvotes: 0
Views: 210
Reputation: 91
The issue is the String output
only exists within the for statement, it needs to be created outside of it, ideally using stringbuilder:
String myConcat(String[] arguments, String separator){
StringBuilder output = new StringBuilder();
for(int i = 0; i < arguments.length; i++){
output.append(arguments[i]);
output.append(separator);
}
return output.toString();
}
You seem to want the trailing separator, if unneeded you could remove it with an if statement
Upvotes: 1
Reputation: 26
First, StringBuilder is prefered than + operation.
Second, it is a mistake to define String output in the loop body which does not save the value actually.
Third, need consider the border, i.e. no separator should be appended for the last element of the argument array.
Fourth, it is i < arguments.length
, not i <= arguments.length
String myConcat(String[] arguments, String separator) {
StringBuilder output = new StringBuilder();
for(int i = 0; i < arguments.length; i++){
output.append(arguments[i]);
if(i < arguments.length-1){
output.append(separator);
}
return output.toString();
}
Upvotes: 1
Reputation: 143
String output = arguments[0] + separator;
arguments[0] -> arguments[i] and the String output var must be defined out the for{}
the error tip is very obvious.
Upvotes: 1