gpt4 book ai didi

java - 了解 Java 中的 If 语句

转载 作者:行者123 更新时间:2023-11-29 03:22:01 25 4
gpt4 key购买 nike

我在理解以下代码时遇到问题:

public class TestIf {


public static void main(String[] args) {
if (true){
if (false){
System.out.println("true false");
}

else{
System.out.println("true true");
}

}

}

当我运行它时,它打印出 true true。

我不明白为什么首先要执行这段代码:

if(true)

如果这里到底是真的是什么?这不像是声明了一个 boolean 值,例如

boolean bol = true;

if (bol == true) {
//execute the rest of the code
}

最佳答案

如果 if 中的表达式被评估为 true,则输入 if

boolean bol = true;

if (bol == true) {

上面发生了什么? bol 是否等于 true?是的。所以(bol==true)等价于只写(true)

所以上面的代码是一样的

if (true) {

现在考虑您的代码。

    if (true){ // enters 'if' since value of expression inside 'if' is true
if (false){ // goes to else
System.out.println("true false");
}

else{
System.out.println("true true"); // prints
}

}

关于java - 了解 Java 中的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23042642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com