I wrote the following program to display all prime numbers between 2 and 50 (inclusive). The program ran as intended but when I reexamined the code I wondered why it had not failed. The if statement can change the value of the isprime variable. However, is this change not forgotten once the inner for code block {} is left? This would mean that isprime would remain true and all numbers would be displayed.
class Prime {
public static void main (String args []) {
int a, b;
boolean isprime;
for (a = 2; a < 51; a++) {
isprime = true;
for (b = a-1; b > 1; b--) {
if (a % b == 0) isprime = false;
}
if (isprime) System.out.println(a);
}
}
}
解决方案
Well, as you see, that's not how it works: the scope of the variable is the block where it is declared, including any sub block.
Modifying the variable in a sub block modifies it for all of its scope. A copy of the variable is not made everytime a new block starts.