简体   繁体   English

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

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

I'm working in TicTacToe gui program in java. 我正在用Java的TicTacToe gui程序工作。 I have created a class PlayerTurn . 我创建了一个类PlayerTurn In order to check for the player turn I used player = (player%2) ? 1 : 2; 为了检查玩家回合,我使用player = (player%2) ? 1 : 2; player = (player%2) ? 1 : 2; in java. 在Java中。 I used in a C++ project and it worked fine but in Java I get error Type Mismatch : Cannot convert from int to boolean I have declared player as an int. 我在C ++项目中使用过,但工作正常,但在Java中出现错误Type Mismatch:无法从int转换为boolean,我已将player声明为int。

You need to compare the result of the modulo operation to something, since the condition in a ternary expression has to be a boolean . 您需要将模运算的结果与某些结果进行比较,因为三元表达式中的条件必须是boolean I am guessing you want to compare with 1 : 我猜您想与1比较:

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

In the ternary operator: 在三元运算符中:

    result = testCondition ? value1 : value2

testCondition has to be a boolean value. testCondition必须为boolean值。 If testCondition evaluates to true , then result = value1 . 如果testCondition评估为true ,则result = value1 Else, result = value2 . 否则, result = value2

Therefore, player = (player%2) ? 1 : 2 因此, player = (player%2) ? 1 : 2 player = (player%2) ? 1 : 2 doesn't work.( Type Mismatch : Cannot convert from int to boolean ) (player%2) is an int, not a boolean value. player = (player%2) ? 1 : 2不起作用。( 类型不匹配:无法从int转换为boolean(player%2)是int,而不是布尔值。 Change it to: 更改为:

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

Translates to: 转换为:

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

Here's a good example: 这是一个很好的例子:

min_Val = a < b ? a : b;

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

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