语句中的Java布尔不起作用

语句中的Java布尔不起作用

本文介绍了'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

[例如:当mouseClicked时:如果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)

将始终为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布尔不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:16