简体   繁体   中英

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

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM