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