I'm trying to create a program where you can add Student info with their address. Therefor I have created 2 classes, class Student and class Adres (dutch for address). In the Adres class I have the address data and in Student the student data.
But i'm getting stuck at creating a constructor for my Student class because when you add a new student the address of that student also needs to be added.
And I'm trying to use the toString method in Student, but the address needs to be returned aswell.
So I have 3 questions:
- How to set up the constructor for class Student where the address also needs to be added
- how to set up the toString method where it also returns the "toString" from Adres.
- How do I input the LocalDate and address when adding a new student. (localdate is used for the students birthday)
I'm fairly new to java and if someone could help me that would be awesome.
My Adres class:
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}");
}
}
My Student class:
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"));
}
}
And my main class where I try to add a student
package oop3.studenten;
public class Main {
public static void main(String[] args) {
Student student = new Student(500739074, "Ronny", "Giezen", 22111997, "?"
);
}
}
Thanks in advance