Java代码不会改变人类岁月的年龄

问题描述 投票:-1回答:1

我正在尝试做一个程序,将输入的狗的年龄转换成人类的岁月,但这是行不通的。以下是我将狗年转换为人年的说明:一种方法[[inHumanYears,该方法将返回宠物狗的年龄(以人为单位)。这是计算方法:

    15人年等于中型犬生命的第一年。
  • [狗的第二年相当于一个人的九年。
  • 此后,每条狗的人年寿命约为5年。
  • 这里有几个例子:

      [4个月大的狗= 0.25(一年的1/4)* 15 = 3.75人年]
  • 5岁= 15 + 9 +(5-2)* 5 = 39人年
  • 有人可以帮我吗?这是我到目前为止得到的代码:

    java.util.Scanner; public class MyPet_1_lab7 { // Implement the class MyPet_1 so that it contains 3 instance variables private String breed; private String name; private int age; private double inHumanYears; // Default constructor public MyPet_1_lab7() { this.breed = null; this.name = null; this.age = 0; } // Constructor with 3 parameters public MyPet_1_lab7(String a_breed, String a_name, int an_age){ this.breed = a_breed; this.name = a_name; this.age = an_age; } // Accessor methods for each instance variable public String getBreed(){ return this.breed; } public String getName(){ return this.name; } public int getAge(){ return this.age; } //Mutator methods for each instance variable public void setBreed(String a_breed){ this.breed = a_breed; } public void setName(String a_name){ this.name = a_name; } public void setAge(int an_age){ this.age = an_age; } // toString method that will return the data in an object formated as per the output public String toString(){ return (this.breed + " whose name is " + this.name + " and " + this.age + " dog years (" + inHumanYears + " human years old)"); } public boolean equals(MyPet_1_lab7 a){ if ((this.breed == a.getBreed()) && (this.age == a.getAge())){ return true; } else return false; } public double inHumanYears(){ if (age >= 2 ){ inHumanYears = (15 + 9 + (age - 2))*5; return (inHumanYears); } else { inHumanYears = (age/12)*15; return (inHumanYears); } } public static void main(String[] args) { Scanner keyboard = new Scanner (System.in); System.out.print("What type of dog do you have? "); String breed = keyboard.nextLine(); System.out.print("What is its name? "); String name = keyboard.nextLine(); System.out.print("How old? "); int age = keyboard.nextInt(); MyPet_1_lab7 dog= new MyPet_1_lab7(); System.out.println(dog); MyPet_1_lab7 dog1 = new MyPet_1_lab7(breed,name,age); System.out.println(dog1); } } '''

  • java calculator converters
    1个回答
    0
    投票
    问题是您的toString()方法使用尚未调用的方法访问您的

    set字段。这个

    public String toString(){ return (this.breed + " whose name is " + this.name + " and " + this.age + " dog years (" + inHumanYears + " human years old)"); }
    应更改为调用inHumanYears()。喜欢,

    public String toString(){ return (this.breed + " whose name is " + this.name + " and " + this.age + " dog years (" + inHumanYears() + " human years old)"); }

    © www.soinside.com 2019 - 2024. All rights reserved.