增加双变量值并在java

时间:2018-04-06 20:13:29

标签: java oop

我正在创造一种方法,应该增加重量变量值并打印大象已经吃了7.5公斤的食物,现在称重(新的重量)。 我对java很新,会感激任何帮助。感谢。

public class Elephant {

public static void main(String[] args) {
}// end of main
// instance variables

private String name ;
private double weight ;

// constructor
public Elephant(String name, double weight) {
    this.name = "elly";
    this.weight = 100;
}// end constructor
    // getter method

public String getName() {
    return name;
}

public double getWeight() {
    return weight;
}

// setter method
public void setName(String name) {
    this.name = name;
}

public void setWeight(double weight) {
    this.weight = weight;
}

public void Eatting(double kilosOfFood) {
    double consumed = weight + 7.5;
    System.out.println("The eleaphan has eating" +weight +" kilograms of 
    food and now weighs " + consumed + "Kg");
}
}// end of class

2 个答案:

答案 0 :(得分:1)

修改main方法以调用对Eatting方法的调用:

public static void main(String[] args) {
   Elephant elephant = new Elephant("name",10.0D);//with which you want to insantiate the elephant object
   elephant.Eatting(7.5);
 }

另外,更改Eatting方法以使用传递的参数。

public void Eatting(double kilosOfFood) {
    double consumed = weight + kilosOfFood;
    System.out.println("The eleaphan has eating" +kilosOfFood+" kilograms of food and now weighs " + consumed + "Kg");
}

答案 1 :(得分:1)

我不明白你打算用Eatting方法中的double kilosOfFood参数做什么。

It should have been 

public void Eatting(double kilosOfFood) {
            double consumed = weight + kilosOfFood;
            System.out.println("The eleaphan has eating " + this.weight + "kilograms of food and now weighs " + consumed + "Kg");
        }

但下面会正确编译

public class Elephant {
        private String name ;
    private double weight ;

    // constructor
    public Elephant(String name, double weight) {
        this.name = name;
        this.weight = weight;
    }// end constructor
        // getter method

    public String getName() {
        return name;
    }

    public double getWeight() {
        return weight;
    }

    // setter method
    public void setName(String name) {
        this.name = name;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public void Eatting(double kilosOfFood) {
        double consumed = weight + 7.5;
        System.out.println("The eleaphan has eating " + this.weight + "kilograms of food and now weighs " + consumed + "Kg");
    }

        public static void main(String args[]) {
           Elephant e = new Elephant("EE", 10.00);
           e.Eatting(2.5);
        }
    }


    The eleaphan has eating 10.0kilograms of food and now weighs 17.5Kg

您需要更改主要方法,并更正语法。