如何在java中更新/更改示例变量((初级)

twh00eeo  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(516)

我是java新手,我正在尝试创建一个方法来更新对象的示例变量age。我正在编译代码,但是我没有看到年龄值的变化。此代码是赋值的一部分,因此我无法更改构造函数。我编写的更新年龄的方法(不起作用)如下所示。我的全部代码如下所示。我也很好奇是否有一种方法可以只更新/更改我的一个对象,但是在我这样做之前,我需要一种方法来处理这两个对象。如果您能帮助正确编写此方法,我们将不胜感激!

public void setnewAge(int age) {
    dogAge += 1;
    this.dogAge = dogAge;
}

下面是我的全部代码(包括我为更新age而编写的方法)。

public class Dog {
    //Instance Varibles
    private String dogName; 
    private int dogAge;
    private int dogWeight;

    //Two Contructors (One Completely Empty)
    public Dog() {
    }  

    public Dog(String name, int age, int weight){
        dogName = name;
        dogAge = age;
        dogWeight = weight;
    }   

    //Getters
    public String getName() { return dogName;}
    public int getAge() { return dogAge;}
    public int getWeight() { return dogWeight;}

    //Setters
    public void setName(String theName) { dogName = theName;}
    public void setAge(int theAge) {dogAge = theAge;}
    public void setWeight(int theWeight) {dogWeight = theWeight;}

    //to(String) method
    public String toString() {
        return  "The dogs's name is " + getName() + ", the dogs's age is " +
                getAge() + ", " + "\n" + "the dogs's weight is " + getWeight() + ".";
    }

    public void setnewAge(int age) {
        dogAge += 1;
        this.dogAge = dogAge;
    }       

    //Main Method
    public static void main(String[] args) {
        Dog poodle = new Dog("Bob", 5, 26);
        System.out.println(poodle);
        Dog lab = new Dog();
        lab.setName("Steve");
        lab.setAge(8);
        lab.setWeight(43);
        System.out.println(lab);
    }
}
cngwdvgl

cngwdvgl1#

正如tom所说,您需要实际调用main函数中的函数,否则将不会有任何更改,而且要优化setnewage函数的代码,请尝试以下操作:

public void setnewAge() {
           this.dogAge = dogAge + 1;
    }

然后在主函数中调用setnewage(),然后打印年龄以查看结果。

Dog poodle = new Dog("Bob", 5, 26);
poodle.setnewAge() ;

相关问题