Brandon Cruz
Brandon Cruz

Reputation: 1

Need to toggle a Boolean in a if else statement

Okay, I need to be able to call a method and toggle a boolean value so that the return is different every time I need to be able to call the method 9 time's and each time switch between returning X, O, X, O, X, O, X, O, X

public class XOChecker {
    char rX = 'X';
    char rO = 'O';
    char rXO;
    boolean t = true;

   public char setXO() {

       if (t==true) {

       rXO = rX;

       } else if (t==false) {

       rXO = rO;

       }
       return rXO;
   }  

}

Upvotes: 0

Views: 2938

Answers (5)

starblue
starblue

Reputation: 56832

  • Declare constants as static final (or get rid of them completely).

  • Declare everything used only internally private.

  • Unlike other replies, don't do assignment inside expressions.

  • Use more meaningful names.

Here goes:

public class XOChecker
{
    private static final char REPLY_TRUE = 'X';
    private static final char REPLY_FALSE = 'O';

    private boolean t = true;

    public char toggle()
    {
        final char result = t ? REPLY_TRUE : REPLY_FALSE;
        t = !t;
        return result;
    }
}

Upvotes: 0

MByD
MByD

Reputation: 137442

how about:

return (t = !t) ? rO : rX;
//        ^ invert t every time
//                   ^ t changes every time, so the return value changes every time

the following code:

public class XOChecker {
    char rX = 'X';
    char rO = 'O';
    boolean t = true;

    public char setXO() {
        return (t = !t) ? rX : rO;
    }  

    public static void main(String [] args) {
        XOChecker xo = new XOChecker();
        for (int i = 0; i < 100 ; ++i) {
            System.out.print(xo.setXO());
        }
    }
}

outputs:

OXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX

Upvotes: 3

Vlad
Vlad

Reputation: 18643

public class XOChecker {

    char xo = 'O';

    public char setXO(){
        xo = (xo=='O')?'X':'O';
        return xo;
    }

}

Alternatively: xo = (char)('X'-xo+'O');

And finally: xo^='X'^'O';

Or shorter:

public char setXO(){
    return xo^=23;
}

Upvotes: 2

Swagatika
Swagatika

Reputation: 3436

The problem with your attempt is :

You are not changing value of t, after calling the method. Also else if (t==false) is equivalent to else

You have the change the value of t each time you call the method. Something like :

if(t)
{
   t = false;
   return rX;
}
else
{
   t = true;
   return rO;
}

Upvotes: 0

TotoroTotoro
TotoroTotoro

Reputation: 17622

t = !t;
if(t) {
  return rX;
} else {
  return rO;
}

BTW, the name of the method is misleading. It should be getSomething, not setSomething, based on what it does.

Upvotes: 1

Related Questions