gpt4 book ai didi

java - 我正在尝试打印我创建的对象 person p1 的地址 a1 。 Person 构造函数也接受 Address 对象

转载 作者:行者123 更新时间:2023-12-01 16:51:46 24 4
gpt4 key购买 nike

public class Person {
enum Sex{Male, Female}

private String initials;
private String lastname;
private String firstname;
private Sex sex;
private int yearOfBirth;
private double netWorth;
private Address homeaddress;
Sex male = Sex.Male;
Sex female = Sex.Female;

public Person(){}

public Person(String firstname, String lastname, int yearOfBirth, Sex sex, double netWorth, Address homeaddress)
{
this.netWorth = netWorth;
this.firstname = firstname;
this.lastname = lastname;
this.sex = sex;
this.homeaddress = homeaddress;
this.male = Sex.Male;
this.female = Sex.Female;
}
public void updateNetworth(double x)
{
this.netWorth = netWorth + x;
}

public String toString(){
return("\nName: " + this.firstname + this.lastname + "\n" +
"Address: " + this.homeaddress + "\nNet Worth: " + this.netWorth);
}
public static void main(String[] args)
{
Address a1 = new Address (258, "Masachu","New York","USA");
Person p1 = new Person("John","Brown",1998,Sex.Male,1000.00,a1);
System.out.println(p1.toString());
p1.updateNetworth(1000.00);
System.out.println(p1.toString());
}

}

public class Address {
private int streetNumber;
private String streetName;
private String city;
private String country;

public Address (int streetNumber, String streetName, String city, String country)
{
this.streetNumber = streetNumber;
this.streetName = streetName;
this.city = city;
this.country = country;
}

}

每当我运行此命令时,我的地址字段都会被打印为 Address@3feba861。我不清楚为什么会这样。所以我的 Person 构造函数接受 Address 对象,但似乎我无法以这种方式打印出带有地址的 person 对象。我该如何解决这个问题。

最佳答案

@Override
public String toString() {
return "Address{" +
"streetNumber=" + streetNumber +
", streetName='" + streetName + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}

关于java - 我正在尝试打印我创建的对象 person p1 的地址 a1 。 Person 构造函数也接受 Address 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61670817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com