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

江枫思渺然 提交于 2020-02-16 06:50:31

问题


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

[ex: When mouseClicked:If playerOne is true, then do something, and set playerOne to false and playerTwo to true].

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

Thanks in advance, Tom!


回答1:


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.




回答2:


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.




回答3:


You are using an assignment here

if (playerTwo = true)

replace with

if (playerTwo == true)

or better

if (playerTwo)


来源:https://stackoverflow.com/questions/14094558/java-boolean-in-if-statement-not-functioning

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