【问题标题】:cannot convert from int to boolean. Java Error (New Case)无法从 int 转换为 boolean。 Java 错误(新案例)
【发布时间】:2015-01-04 16:25:14
【问题描述】:

我正在使用 java 中的 TicTacToe gui 程序。我创建了一个类PlayerTurn。为了检查玩家回合,我在 java 中使用了player = (player%2) ? 1 : 2;。我在 C++ 项目中使用过,它运行良好,但在 Java 中出现错误 Type Mismatch : Cannot convert from int to boolean 我已将 player 声明为 int.

【问题讨论】:

  • (player%2)的结果类型是什么? ?: 的第一个操作数必须是什么类型?
  • 欺骗:Type mismatch: cannot convert from integer to boolean - 虽然我不想以我自己的观点关闭它......
  • @MirwiseKhan:好的,请看我更新的答案。如果这能回答您的问题,请告诉我。

标签: java int boolean


【解决方案1】:

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

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

【讨论】:

  • 他很可能在!= 0之后,因为在许多类似C的语言中,0代表false
  • @amit:是的,我也意识到了。
【解决方案2】:

在三元运算符中:

    result = testCondition ? value1 : value2

testCondition 必须是 boolean 值。如果testCondition 计算为true,则result = value1。否则,result = value2

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

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

翻译为:

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

这是一个很好的例子:

min_Val = a < b ? a : b;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2021-05-31
    • 1970-01-01
    • 2023-02-02
    • 2015-11-09
    • 2012-11-03
    • 1970-01-01
    相关资源
    最近更新 更多