简体   繁体   English

需要在if else语句中切换布尔值

[英]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 好的,我需要能够调用一个方法并切换一个布尔值,以便每次需要调用9次方法以及每次在返回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'); 或者: xo = (char)('X'-xo+'O');

And finally: xo^='X'^'O'; 最后: 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. 基于它的作用,应该是getSomething ,而不是setSomething

The problem with your attempt is : 您尝试的问题是:

You are not changing value of t, after calling the method. 调用方法后,您不会更改t的值。 Also else if (t==false) is equivalent to else 如果(t == false)else等价

You have the change the value of t each time you call the method. 每次调用该方法时,您都会更改t的值。 Something like : 就像是 :

if(t)
{
   t = false;
   return rX;
}
else
{
   t = true;
   return rO;
}
  • Declare constants as static final (or get rid of them completely). 将常量声明为static final (或完全摆脱它们)。

  • Declare everything used only internally private . 声明仅在内部使用的一切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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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