以下是我目前在代码中的内容
public class Person {
public Person()
{
String person = "";
int age = 0;
String city = "";
int sibCount = 0;
// make an instance field for name, city, age, and siblingCount
Person person = new Person();
Person age = new Person();
Person city = new Person();
Person sibCount = new Person();
}
// make a method called parseCommaDelim
public void parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}
}
我正在尝试返回一个人实例,我不知道该怎么做。我试过回复人;'我的代码不喜欢它。
我的toString方法不起作用,因为它不知道什么人,年龄或城市,我不知道为什么。
答案 0 :(得分:1)
您想要达到的目标可能是以下几点:
public class Person {
// fields
private String person = "";
private int age = 0;
private String city = "";
private int sibCount = 0;
// constructor
public Person() {
}
// public access methods (getters)
public String getPerson() {
return this.person;
}
public int getAge() {
return this.age;
}
public String getCity() {
return this.city;
}
public int getSibCount() {
return this.sibCount;
}
// toString
public String toString() {
return "person: " + person + ", age: " + age + ", city: " + city;
// factory method
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
Person instance = new Person();
instance.person = tokens[0];
instance.age = Integer.parseInt(tokens[1];
instance.city = tokens[2];
// ...
return instance;
}
}
字段person
应该重命名为name
。根据你想要使你的类不可变的不同你可能想要添加一个以所有参数作为参数的构造函数:
public Person(String name, int age, String city, int sibCount) {
this.name = name;
this.age = age;
this.city = city;
this.sibCount = sibCount;
}
或为changable字段添加setter,例如:
public void setCity(String city) {
this.city = city;
}
顺便说一句。使用上面的构造函数,您可以将工厂修改为以下稍微清晰的代码:
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
String person = tokens[0];
int age = Integer.parseInt(tokens[1];
String city = tokens[2];
int sibCount = Integer.parseInt(tokens[3]);
return new Person(person, age, city, sibCount);
}
答案 1 :(得分:0)
public class Person {
public String person;
public int age;
public String city;
public int sibCount;
public Person()
{
person = "";
age = 0;
city = "";
sibCount = 0;
}
// make a method called parseCommaDelim
public String parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}