Java Boolean In 'IF' Statement Not Functioning [closed]

ⅰ亾dé卋堺 提交于 2019-12-02 13:31:04

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)

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);
       }
    }

as the something == true would be redundant.

if(playerTwo = true)

== not =.

Wouldn't it be simpler to have a "currentPlayer" integer that is either 1 or 2 instead though? This would also prevent the (presumably impossible) state of having both players active at once.

You are using an assignment here

if (playerTwo = true)

replace with

if (playerTwo == true)

or better

if (playerTwo)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!