Phi*_*ger 1 java variables for-loop boolean
我有这个代码片段:
private static int counter = 0;
public static void main(String[] args) {
int x = 1;
for (test('1'); test('2') && (x <= 2); test('3'))
{
x++;
test('4');
}
System.out.println(" Counter=" + counter);
}
static boolean test(char num)
{
System.out.print(" " + num);
counter++;
return true;
}
Run Code Online (Sandbox Code Playgroud)
为什么for循环在这里?我认为for循环中的第一个语句必须是变量的初始化,并且这不会编译,但它会运行并输出输出:
1 2 4 3 2 4 3 2 Counter=8
Run Code Online (Sandbox Code Playgroud)
这是boolean做什么的?
"initialization"语句(test('1')在本例中)可以是任何语句列表(参见下面的JLS链接); 它不需要实际上是初始化.
test('2') && (x <= 2)在每次循环迭代之前,将按照惯例评估条件,直到它变为假.增量test('3')将在每次迭代后执行.
这在JLS§14.14.1中有详细说明.
让我们手工完成它:
test(1) 叫
1打印并counter设置为1test('2') && (x <= 2)执行
2打印并counter设置为2truex++:x设置为2test(4) 叫
4打印并counter设置为3test('3')称为
3打印并counter设置为4test('2') && (x <= 2)执行
2打印并counter设置为5truex++:x设置为3test(4) 叫
4打印并counter设置为6test('3')称为
3打印并counter设置为7test('2') && (x <= 2)执行
2打印并counter设置为8false,因为x现在是3