首页 > 解决方案 > 为什么 for 循环可以保存返回的布尔值但不能保存原始布尔值?

问题描述

看一下以下代码片段的for 循环。

class Practice
{ 
    static boolean foo(char c){
        System.out.print(c); 
        return true; 
    } 
    public static void main( String[] args ){
        int i = 0; 
        for (foo('A'); foo('B') && (i < 2); foo('C')){
            i++; 
            foo('D'); 
        } 
    } 
}

这部分代码在编译执行时不会报错。即使它从函数中获取布尔值

for (foo('A'); foo('B') && (i < 2); foo('C')){
     i++; 
     foo('D'); 
} 

虽然这是一个错误,

boolean b = true;

for (b;some_condition;b){

    //statements

}

// or,

for (true;some_condition;true){

    //statements

}

标签: javafor-loopboolean

解决方案


这是来自 Oracle 的 java 官方语法:

ForControl:
    ForVarControl
    ForInit ; [Expression] ; [ForUpdate]

ForVarControl:
    {VariableModifier} Type VariableDeclaratorId  ForVarControlRest

ForVarControlRest:
    ForVariableDeclaratorsRest ; [Expression] ; [ForUpdate]
    : Expression

ForVariableDeclaratorsRest:
    [= VariableInitializer] { , VariableDeclarator }

ForInit: 
ForUpdate:
    StatementExpression { , StatementExpression } 

据我了解 ForInit 和 ForUpdate 期望一个语句,而不是像这样的文字值true或像b.

https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html


推荐阅读