【发布时间】:2020-02-26 22:24:10
【问题描述】:
我正在尝试创建一个程序,您可以在其中添加学生信息及其地址。为此,我创建了 2 个班级,Student 班级和 Adres 班级(地址为荷兰语)。 在 Adres 类中,我有地址数据,在 Student 中有学生数据。
但是我在为我的 Student 类创建构造函数时遇到了困难,因为当您添加新学生时,还需要添加该学生的地址。
我正在尝试在 Student 中使用 toString 方法,但地址也需要返回。
所以我有 3 个问题:
- 如何为需要添加地址的Student类设置构造函数
- 如何设置 toString 方法,它还从 Adres 返回“toString”。
- 添加新学生时如何输入本地日期和地址。 (localdate 用于学生生日)
我对 java 还很陌生,如果有人可以帮助我,那就太棒了。
我的地址课:
package oop3.studenten;
public class Adres {
private String straat;
private Integer huisnr;
private String postcode;
private String plaats;
public Adres(String straat, Integer huisnr, String postcode, String plaats) {
this.straat = straat;
this.huisnr = huisnr;
this.postcode = postcode;
this.plaats = plaats;
}
public String toString() {
return straat + "" + huisnr + "," + postcode + "" + plaats;
}
// Using regex to check if postcode is valid
public static boolean checkPostcode(String postCode) {
return postCode.matches("[1-9][0-9]{3}[a-zA-Z]{2}");
}
}
我的学生班级:
package oop3.studenten;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Student {
private Integer studentnr; //StudentId
private String voornaam; //Firstname
private String achternaam; //Lastname
private LocalDate geboortedatum; //Birthday
private Adres adres; //address
// constructor for Student
public Student(Integer studentnr, String voornaam, String achternaam, LocalDate geboortedatum, Adres adres){
this.studentnr = studentnr;
this.voornaam = voornaam;
this.achternaam = achternaam;
this.geboortedatum = geboortedatum;
this.adres = new Adres();
}
// toString method for Student
@Override
public String toString() {
return "Student{" +
"studentnr=" + studentnr +
", voornaam='" + voornaam + '\'' +
", achternaam='" + achternaam + '\'' +
", geboortedatum=" + korteGeboortedatum(geboortedatum) +
", adres=" + adres +
'}';
}
// method to return birthday (geboortedatum) in day month year format
public String korteGeboortedatum(LocalDate gebdatum ){
return gebdatum.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
}
}
还有我尝试添加学生的主要课程
package oop3.studenten;
public class Main {
public static void main(String[] args) {
Student student = new Student(500739074, "Ronny", "Giezen", 22111997, "?"
);
}
}
提前致谢
【问题讨论】:
-
在 Student 中,您传递了一个 Adres 参数,但随后您创建了一个分配给 adres 字段的新参数。这没有意义
-
我不明白你关于 toString() 的问题,虽然 Adres 没有像 Student 那样使用前缀,但没关系,尽量保持一致。
-
您应该添加
new Adres("...")来代替问号。然后将this.adres = new Adres()替换为this.adres = adres。顺便说一句,并非所有地址都与该系统兼容。例如,您将如何存储 Kalverstraat 165B? -
对于 geboortedatum,请阅读文档,您可以执行 LocalDate.of(1997, 11, 22)
标签: java constructor tostring