繁体   English   中英

无法从int转换为boolean。 Java错误(新案例)

[英]cannot convert from int to boolean. Java Error (New Case)

我正在用Java的TicTacToe gui程序工作。 我创建了一个类PlayerTurn 为了检查玩家回合,我使用player = (player%2) ? 1 : 2; player = (player%2) ? 1 : 2; 在Java中。 我在C ++项目中使用过,但工作正常,但在Java中出现错误Type Mismatch:无法从int转换为boolean,我已将player声明为int。

您需要将模运算的结果与某些结果进行比较,因为三元表达式中的条件必须是boolean 我猜您想与1比较:

player = (player%2 == 1) ? 1 : 2;

在三元运算符中:

    result = testCondition ? value1 : value2

testCondition必须为boolean值。 如果testCondition评估为true ,则result = value1 否则, result = value2

因此, player = (player%2) ? 1 : 2 player = (player%2) ? 1 : 2不起作用。( 类型不匹配:无法从int转换为boolean(player%2)是int,而不是布尔值。 更改为:

player = (player%2 == 1) ? 1 : 2

转换为:

Is player%2 == 1?
   Yes?  Then player = 1
   No?   Then player = 2

这是一个很好的例子:

min_Val = a < b ? a : b;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM