【问题标题】:How does a returning Boolean work in an argument (Java)返回的布尔值如何在参数中工作(Java)
【发布时间】:2015-02-02 00:56:09
【问题描述】:

所以下面的代码:

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

基本上说两个整数(已经实例化并且已经定义了next)next 和last 被更改,以便last 是next,然后next 是随机生成的,因此它不是以前的数字。然后guesslow和guesshigh返回如果next>last或next我的问题是它返回什么?它返回真还是假?或者像一个数字? 在我的代码的另一部分:

public void update(boolean arg) //arg 为真表示玩家猜对了 {

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

我将如何编写 if 语句,以便如果guessLow 或guessHigh 为真则执行此操作,否则执行此操作? 非常感谢您的帮助

【问题讨论】:

    标签: java boolean arguments


    【解决方案1】:

    基于arg参数的定义; true 如果玩家猜对了。而arg 将是truefalse

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

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

    你也可以像这样颠倒逻辑

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

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

    【讨论】:

      【解决方案2】:

      这两个方法返回一个布尔值。在 if 语句中,您只需将方法的名称写为:

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

      或者如果你把它作为一个参数:

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

      在这种情况下,我建议使用更有意义的名称调用参数,例如猜对了。所以你可以把 if 语句写成

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

      请参阅 Oracle 的 official tutorial 关于 if-then-else。

      【讨论】:

      • 我想你的意思是if(guessHigh()){...}
      猜你喜欢
      • 2013-03-28
      • 2015-02-14
      • 2021-04-04
      • 2015-04-07
      • 2021-01-05
      • 1970-01-01
      • 2016-07-11
      • 2015-01-04
      • 2016-09-03
      相关资源
      最近更新 更多