【问题标题】:feed method java if-statement提要方法 java if 语句
【发布时间】:2014-03-31 21:09:10
【问题描述】:

decHungry() 减少饥饿值 10,incEnergy() 增加能量值 10。我想确保饥饿值不会超过 0 到负数,并且能量值不会超过 100。我怎么做?

protected void feed() {
    System.out.println("\nEating..."); 
    if (hungry <= 90 && hungry >= 0) {
        decHungry();
        incEnergy();
        System.out.println("I've just ate dumplings, my current energy state is " + energy + " and hungry state is " + hungry);
    }
    else { 
        System.out.println ("I have ate enough!"); 
    }
}

【问题讨论】:

    标签: java if-statement methods


    【解决方案1】:

    在调用该函数之前,您要确保饥饿值大于或等于 10 并且能量小于或等于 90。

    if(hungry >= 10){
        decHungry();
    }
    if(energy <=90){
        incEnergy();
    }
    

    【讨论】:

      【解决方案2】:

      最简单的方法可能是在最后添加一个检查以查看您是否超出范围,如果超出,则将自己返回到范围内。

      if(hungry<0)hungry=0;
      if(energy>100)energy=100;
      

      【讨论】:

      • 如果我将 syso cmets 添加到这些语句中,它不会覆盖我现有的 syso?
      • @user3482500 syso 是什么?
      【解决方案3】:

      您应该在调用decHungryincEnergy 方法之后检查。如果饥饿或能量水平超过限制,则将其设置为限制值:

      protected void feed() {
          System.out.println("\nEating...");
      
          decHungry();
          incEnergy();
      
          if (hungry < 0)
              hungry = 0;
      
          if (energy > 100)
              energy = 100;
      
          // ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-01
        • 2010-12-09
        • 2013-10-24
        • 1970-01-01
        • 1970-01-01
        • 2013-11-24
        • 1970-01-01
        • 2012-10-25
        相关资源
        最近更新 更多