資料內(nèi)容:
When you declare a variable in the first slot of the for statement, the scope
of that variable extends until the end of the body of the for loop.
for (int i = 1; i <= 10; i++)
{
. . .
}
// i no longer defined here
In particular, if you define a variable inside a for statement, you cannot use
its value outside the loop. Therefore, if you wish to use the final value of a
loop counter outside the for loop, be sure to declare it outside the loop
header.
int i;
for (i = 1; i <= 10; i++)
{
. . .}
// i is still defined here
On the other hand, you can define variables with the same name in separate
for loops:
for (int i = 1; i <= 10; i++)
{
. . .
} . . .
for (int i = 11; i <= 20; i++) // OK to define another variable
named i
{
. . .
}
A for loop is merely a convenient shortcut for a while loop. For example,
for (int i = 10; i > 0; i--)
System.out.println("Counting down . . . " + i);
int i = 10;
while (i > 0)
{
System.out.println("Counting down . . . " + i);
i--;
}