Java Boolean In #39;IF#39; Statement Not Functioning(IF 语句中的 Java 布尔值不起作用)
问题描述
很遗憾,下面的代码片段无法正常运行.它附加到 JLabel 上,以便在单击时注意到 PlayerOne 或 PlayerTwo 是否正在播放,并相应地重新排列它们的布尔值
Unfortunately the snippet of code below is not functioning as it should. It's attached to a JLabel so that when clicked, notices whether PlayerOne or PlayerTwo is playing, and re-arranges their boolean values accordingly
[例如:当鼠标点击时:如果 playerOne 为 true,则做某事,将 playerOne 设置为 false,将 playerTwo 设置为 true].
[ex: When mouseClicked:If playerOne is true, then do something, and set playerOne to false and playerTwo to true].
所以,当 mouseClicked 被激活时,它会交换它们的值!
So, it swaps their values when mouseClicked is activated!
public void mouseClicked(MouseEvent arg0) {
if(playerOne = true){
playerOne = false;
playerTwo = true;
boxOne.setIcon(xIcon);
} else { if(playerTwo = true){
playerOne = true;
playerTwo = false;
boxOne.setIcon(oIcon);
}}
提前致谢,汤姆!
推荐答案
在java中,测试两个项目是否相等的操作数是==而不是'=',这是一个赋值;赋值返回分配的值,所以你的:
in java the operand to test equality between two items is == not '=' which is an assignment; an assignment returns the assigned value, so your :
if (playerOne = true)
将始终为真,因为 playerOne 将被分配给 true
,然后 if 将变为 if (true)
,并且将始终执行关联的语句.
will always be true as playerOne will be assigned to true
, then the if will become if (true)
and the statement associated will always be executed.
重构代码的最佳方法是:
the best way to refactor your code is:
public void mouseClicked(MouseEvent arg0) {
if(playerOne) {
playerOne = false;
playerTwo = true;
boxOne.setIcon(xIcon);
} else if(playerTwo) {
playerOne = true;
playerTwo = false;
boxOne.setIcon(oIcon);
}
}
因为 something == true
将是多余的.
这篇关于'IF' 语句中的 Java 布尔值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'IF' 语句中的 Java 布尔值不起作用
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01