Java对象和构造函数/方法

时间:2015-10-12 21:39:16

标签: java

对我来说,解释我试图让这段代码做的最好方法是复制并粘贴我已经给出的作业。

我自己编写了这个问题然而我遇到的问题是两个变量似乎根本没有加起来,但是当我测试代码时它仍然可以工作。

我想要加起来的两个变量是storePower和strength

创建一个代表超级英雄的类。每个超级英雄都有一个名字。每个超级英雄也都有实力,但这应该是可选的。如果超级英雄没有力量,他们的默认力量应该是10.

每个超级英雄都可以获得一个powerUp,他们的力量会增加一个特定的数量

公共班级超级英雄{

//private instance variables declared below.

//name of the super hero
private String name;
//name of power up variable
private int powerUp;
//name of the strength variable
private int strength;
private int storePower;







/*
Power ups work in a way that if the powerUp is greater then or equal to 10 then add 5 to strength
if the powerUp is greater than  or equal to 5 then add 2 to the strength
if it is less than 5 then add 1 to the strength.
*/

public void powerUp(int powerUp){
this.powerUp = powerUp;
    if(powerUp >= 10){
        storePower = 5;
        strength = storePower + strength;
        //this system out was to test if this bit of code is working.
        System.out.println("Power up is set to 10 or higher!" + " The power is: " + strength);
    }else if(powerUp >= 5){
        storePower = 2;
        strength = storePower + strength;
    }else if (powerUp < 5){
        storePower = 1;
        strength = storePower + strength;
    }else{
        System.out.println("Something is not right..");
    }


}

//constructor for if the player wanted to specify the name and the strength
public Superhero(String name, int strength){
    this.name = name;
    this.strength = strength;

    System.out.println(name + " " + strength);
}



//if the user doesn't enter the strength as it is optional
//this constructor below will run and set the default
public Superhero(String name){
    this.name = name;
    this.strength = 10 + storePower;
    System.out.println(name + " " + strength );
}

} 下面的战斗课

public class Fight{
public static void main(String[] args){

    //creating a new instance of the Superhero object
    Superhero cyclops = new Superhero("cyclops");



    cyclops.powerUp(10);
}

}

在命令行上运行时的输出是:

  

独眼巨人10
  上电设置为10或更高!权力是:5

我想要获得的输出是15,因为加电设置为高于10因此if语句将其设置为5,但是我无法将它们加起来

1 个答案:

答案 0 :(得分:0)

像这样修改你的代码

public void powerUp(int powerUp){
this.powerUp = powerUp;
    if(powerUp >= 10){
        storePower = 5;
          strength  = storePower+powerUp
        //this system out was to test if this bit of code is working.
        System.out.println("Power up is set to 10 or higher!" + " The power is: " + strength  );
    }else if(powerUp >= 5 & powerUp <10){
        storePower = 2;
        strength  =  powerUp+StorePower
 System.out.println("Power up is set to 5 or greater but less than 10!" + " The power is: " + strength  );
    }else if (powerUp < 5){
        storePower = 1;
        Strength  = storePower + powerUp;
 System.out.println("Power up is set to less than 5!" + " The power is: " + strength  );
    }else{
        System.out.println("Something is not right..");
    }

}