I am solving a basic Java string problem on CodingBat.com (extraFront).
The task is to, given a string of any length, return the two first characters repeated three times. This first example is what I ended up doing intuitively:
public String extraFront(String str) {
if (str.length() <= 2){
String front = str;
}else{
String front = str.substring(0,2);
}
return front+front+front;
}
Which gives me an error, front can not be resolved. I guessed that I needed to define the variable outside the loop, so I changed the code to the following, which works without errors:
public String extraFront(String str) {
String front;
if (str.length() <= 2){
front = str;
}else{
front = str.substring(0,2);
}
return front+front+front;
}
What puzzles me is why this should make a difference, as the variable is going to declared anyway, will it not? Is this a peculiarity of how CodingBat handles the code, or is this actually an error? And if it is, why exactly is this incorrect code? And if it is not incorrect, is it bad style?