问题
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?
回答1:
What puzzles me is why this should make a difference, as the variable is going to declared anyway, will it not?
It's a matter of scoping. A variable is only visible within the block where it's declared. This has nothing to do with CodingBat - it's part of the Java language. From section 6.3 of the JLS:
The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).
...
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
I'd also urge you to learn about the conditional operator, which can help in these situations:
String front = str.length() <= 2 ? str : str.substring(0, 2);
回答2:
when you declare a local variable inside a block
,the variable
will only be visible inside that block, as per the scoping
rules of the Java language
you can see a simple video on this :)
A variable is available only from its declaration down to the end of the braces in which it is declared. This region of the program text where the variable is valid is called its scope.
Blocks and statements
来源:https://stackoverflow.com/questions/16040556/declaring-a-variable-inside-of-if-else-construct