Why is my use of the ?: conditional operator incorrect?

前端 未结 4 861
广开言路
广开言路 2021-01-22 07:09

I get a compilation error while trying to compile, \"not a statement\", and the code is:

(checkDatabaseExist())?connectToDB() : buildDB();

when

4条回答
  •  爱一瞬间的悲伤
    2021-01-22 07:17

    As stated in JLS - Section 15.25 - Conditional Operator: -

    It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

    So, you must use an if-else construct to invoke your methods on different condition.

    if (checkDatabaseExist()) {
        connectToDB();
    } else {
        buildDB();
    }
    

提交回复
热议问题