简体   繁体   English

返回的布尔值如何在参数中工作(Java)

[英]How does a returning Boolean work in an argument (Java)

so the below code: 所以下面的代码:

  private void pickNext()
  {

        last = next;
        next = (int)(Math.random() * 9 + 1);
        System.out.print(""+last + next);
        while(last == next)
        {
        next = (int)(Math.random() * 9 + 1);
        }

  }
  public boolean guessHigh()
  {
     pickNext();
     return next > last;
  }
  public boolean guessLow()
  {
     pickNext();
     return next < last;
  }

basically says that two integers (already instantiated and next is defined already) next and last are changed so that last is next, then next is randomly generated so that it is not the previous number. 基本上说改变了两个整数(已经实例化并且已经定义了next)next和last,以便last是next,然后随机生成next,所以它不是前一个数字。 Then guesslow and guesshigh returns if next>last or nextMy question is what does it return? 然后,如果next> last或next,则guesslowlow和guesshigh返回我的问题是什么? does it return true or false? 它返回true还是false? or like a number? 还是喜欢一个数字? In another part of my code: 在我的代码的另一部分中:

public void update(boolean arg) //arg is true means player guessed correct { public void update(boolean arg)// arg为true表示玩家猜测正确{

        if()
        {
           //random other code
        }
        else
        {
          //other code
        }

how would I write the if statement so that if it is the guessLow or guessHigh are true it does this, and if not it does this? 我将如何编写if语句,以便如果它是guessLow或guessHigh为true,则执行此操作,如果不是,则执行此操作? Help is greatly appreciated 非常感谢帮助

The two methods return a boolean. 这两个方法返回一个布尔值。 In the if statement you just write the name of the methods as: 在if语句中,您只需将方法的名称写为:

if ( guessHigh() ) {..}
else {..}

Or if you get it as a parameter: 或者,如果将其作为参数获取:

public void update(boolean arg){
    if ( arg ) {..}
    else {..}
}

In that case I'd suggest to call the parameter with more meaningful name as eg hasCorrectlyGuessed. 在那种情况下,我建议使用更有意义的名称来调用参数,例如hasCorrectlyGuessed。 So you can write the if statement as 因此,您可以将if语句写为

public void update(boolean hasCorrectlyGuessed){
        if ( hasCorrectlyGuessed ) {..}
        else {..}
    }

See official tutorial from Oracle about if-then-else. 请参阅Oracle的有关if-then-else的官方教程

Based on the definition of the arg parameter; 基于arg参数的定义; true if player guessed correctly. 如果玩家猜true则为true And arg will be true or false , argtrue还是false

if (arg) {
    // player guessed correctly.
} else {
    // player guessed incorrectly.
}

which is the same as 这与

if (arg == true) {
    // player guessed correctly.
} else {
    // player guessed incorrectly.
}

You could also reverse the logic like 您也可以颠倒逻辑

if (!arg) {
    // player guessed incorrectly.
} else {
    // player guessed correctly.
}

or 要么

if (arg == false) {
    // player guessed incorrectly.
} else {
    // player guessed correctly.
}

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

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