I am making a Tic Tac Toe game in Java and I need to set the "X" value so that on the 1st, 3rd, 5th, 7th and 9th turn an X is placed in the boxes and when it's the 2nd, 4th, 6th and 8th turn a "O" is placed. If anyone could help it would greatly appreciated
I tried using a counter:
public void onClick(View event) {
// TODO Auto-generated method stub
if (event == btnBox1) {
counter++;
if (counter == 0) {
btnBox1.setText("X");
btnBox1.setEnabled(false);
}
if (counter == 1) {
btnBox1.setText("O");
btnBox1.setEnabled(false);
}
// ...
}
// ...
}
There are two ways to do it:
%
operator. It returns the remainder of the division of two numbers. counter % 2
will be 1 if counter is odd and 0 if counter is even.&
, suggested by Mr. Polywhirl. You could also do (n & 1) == 0
(bit-wise AND) to check for even.Using the modulus operator, your method will be:
public void onClick(View event) {
if (event == btnBox1){
counter++;
if (counter % 2 == 0){
btnBox1.setText("X");
btnBox1.setEnabled(false);
}
if (counter % 2 == 1){
btnBox1.setText("O");
btnBox1.setEnabled(false);
}
}
}