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!
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)
来源:https://stackoverflow.com/questions/14094558/java-boolean-in-if-statement-not-functioning