如何在实例变量中添加数字?

时间:2015-11-16 06:41:11

标签: java instance-variables

public class Geniegotchi {
   private String name = "Bob";
   private int endurance = 4;
   private int happiness = 3; 
   public void setName(String newName){
      name = newName;
   } 
   public void setEndurance(int newEndurance){
   endurance = newEndurance;
   }
   public void setHappiness (int newHappiness){
   happiness = newHappiness;
   }
   public String getName(){
   return name;
   }
   public int getEndurance (){
   return endurance;
   }
   public int getHappiness (){
   return happiness;
   }
   public void genieInfo(){
   System.out.println( "current name: "+this.getName());
   System.out.println( "current happiness level: "+this.getHappiness());
   System.out.println( "current endurance level: "+this.getEndurance());
   }
   public void feed(){
   if (this.getEndurance() <= 10){
   }
   else
     System.out.println("No, thanks...");
   }
   public void play(){
   if (this.getHappiness() < 10){
   }
   else
   System.out.println("No, thanks");
}

void feed()方法,如果耐力是,则将当前耐力提高1 少于10,否则它会在屏幕上显示“No,thanks ...”消息;

void play()方法是将当前的幸福感提高1并将当前的持续时间降低2,如果幸福感小于10,那么否则它打印出一个 屏幕上显示“不,谢谢......”消息;

对于虚空进给和虚空游戏部分,我不知道如何将当前的耐力提高1,并将当前的幸福感提高1并将当前的耐力降低2。 谢谢

1 个答案:

答案 0 :(得分:0)

有几种方法可以增加或减少变量,我的所有例子都会使用你的&#34;耐力&#34;变量,但您可以为任何变量执行此操作。前两个是用于将变量增加/减少某个值的简写方法,最后一个方法显示您还可以在等式中使用变量并将结果存储回同一个变量中。

endurance++;                // increase by 1
endurance--;                // decrease by 1

endurance += 7;             // increase by any number (7 in this example)
endurance -= 7;             // decrease by any number

endurance = endurance + 9;  // increase by any number (9 in this example)
endurance = endurance - 9;  // decrease by any number