gpt4 book ai didi

Java Switch 不兼容类型 Boolean Int

转载 作者:行者123 更新时间:2023-12-01 06:26:22 25 4
gpt4 key购买 nike

我有以下类(class):

public class NewGameContract {

public boolean HomeNewGame = false;

public boolean AwayNewGame = false;

public boolean GameContract(){

if (HomeNewGame && AwayNewGame){
return true;
} else {
return false;
}
}
}

当我尝试像这样使用它时:

            if (networkConnection){

connect4GameModel.newGameContract.HomeNewGame = true;

boolean status = connect4GameModel.newGameContract.GameContract();

switch (status){

case true:
break;

case false:
break;
}
return;
}

我收到错误:

incompatible types found: boolean required: int on the following
`switch (status)` code.

我做错了什么?

最佳答案

您无法打开 boolean 值(无论如何它只有 2 个值):

Java 语言规范明确规定了可以switch-ed 的表达式类型。

JLS 14.11 The switch statement

SwitchStatement:
switch ( Expression ) SwitchBlock

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.

简单地使用 if 语句来区分 boolean 的两种情况会更具可读性和简洁性。

关于Java Switch 不兼容类型 Boolean Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2898068/

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