Using the Adress class in Student class with toString in java - java

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

Student constructor:
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 = adres; //if you do "new Adres();" a completely empty adres instance would be created, instead you want to use the one passed as parameter
}
// toString method for Student
#Override
public String toString() {
return "Student{" +
"studentnr=" + studentnr +
", voornaam='" + voornaam + '\'' +
", achternaam='" + achternaam + '\'' +
", geboortedatum=" + korteGeboortedatum(geboortedatum) +
", adres=" + adres.toString() +
'}'; // ^^ calling the .toString()-method of adres and appending it to the rest
}
Main Class:
public static void main(String[] args) {
Adres adres = new Adres("Mainstreet", 5, "48484", "Amsterdam"); //creating the adress
LocalDate birthday = LocalDate.of(2017, 1, 13); //creating the birthday-localdate
Student student = new Student(500739074, "Ronny", "Giezen", birthday, adres); //passing the birthday & adres to the student-constructor
}

In your Main Class you can create the Address Object first and create the Student after.
In the Student-Constructor you will be able to pass the address object.
public static void main(String[] args) {
Address studentAddress = new Address("straat", 1, "postcode", "plaats")
Student student = new Student(500739074, "Ronny", "Giezen", null, studentAddress);
}
Question
You just call your toString()-Method created in your Address-Class
#Override
public String toString() {
return "Student{" +
"studentnr=" + studentnr +
", voornaam='" + voornaam + '\'' +
", achternaam='" + achternaam + '\'' +
", geboortedatum=" + korteGeboortedatum(geboortedatum) +
", adres=" + adres.toString() +
'}';
}
Question
You have to create a LocalDate Object and pass it in the constructor
public static void main(String[] args) {
Address studentAddress = new Address("straat", 1, "postcode", "plaats")
Student student = new Student(500739074, "Ronny", "Giezen", new LocalDate.now(), studentAddress); // for example
}

Related

Having trouble using the compareTo method

Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```

Avoiding recursion in toString method

this is my huge mindblowing problem with a Java exercise. So, we've got this:
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate
}
and our goal is to overwrite toString method by cutting fields which may lead to recursive infinity. Finally it's supposed to look like a printed object with a name, age, boss and subordinate.
Employee[age=30,name='Mike',boss=Employee[age=45,name='Ann'], subordinate=[Employee[age=25,name='Jimmy']]]
Well, I tried and found that i have no clue how to deal with toString overriding:
import java.util.ArrayList;
import java.util.List;
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
public CyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
public static void main(String[] args) {
CyclicEmployee Mike = new CyclicEmployee(33,"Mike");
Mike.boss = new CyclicEmployee(44,"Ann");
Mike.subordinate = new ArrayList<CyclicEmployee>();
Mike.subordinate.add(new CyclicEmployee(24,"Jim"));
System.out.println(Mike.toString());
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + boss +
", subordinate=" + subordinate +
'}';
}
}CyclicEmployee{age=33, name='Mike', boss=CyclicEmployee{age=44, name='Ann', boss=null, subordinate=null}, subordinate=[CyclicEmployee{age=24, name='Jim', boss=null, subordinate=null}]}
It seems like I should cut all the "null" fields here, but I can't find the way out.
If I understand correctly, you do not want to print null CyclicEmployee objects. You can check if boss and subordinates are null and then if they are skip them in toString(). Since all of them are same type, this method will work for all of them.
#Override
public String toString() {
String str = "";
str = "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'';
if (boss != null) {
str += ", boss=" + boss;
}
if (subordinate.size() != 0) {
str += ", subordinate=" + subordinate;
}
str += '}';
return str;
}
Consider using existing data structure like this or this instead.
But if you really want to use your code, you can create a NonCyclicEmployee class
private static class NonCyclicEmployee {
private int age;
private String name;
public NonCyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
And use it in your toString() of CyclicEmployee.
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
private NonCyclicEmployee ncBoss;
private List<NonCyclicEmployee> ncSubordinate ;
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + ncBoss +
", subordinate=" + ncSubordinate +
'}';
}
And create a method addBoss() and addSubordinate() to create both bosses (boss and ncBoss) and both subordinate at the same time.

NullPointerException when adding Object to ArrayList

I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();

how to create and use a print method using java

Based on the code below, I need to modify the code in the Employee class by creating a specialised print method called employee print() and show how it will be used to print in the employee Test class! Any help please? Here is the code:
class Employee1{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
}
public class employeeTest {
public static void main(String[] args) {
Employee1 emp1 = new Employee1();
emp1.empName = "Sam";
emp1.empNum = "213-23-978";
emp1.empEmailAddress = "sammy#company.za";
Employee1 emp2 = new Employee1();
emp2.empName = "Tasha";
emp2.empNum = "315-90-274";
emp2.yearOfBirth = 1982;
System.out.println("Employee Name: " + emp1.empName);
System.out.println("Employee Number: " + emp1.empNum);
System.out.println("Email Adress: " + emp1.empEmailAddress);
System.out.println("Year of Birth: " + emp1.yearOfBirth);
System.out.println("Employee Name: " + emp2.empName);
System.out.println("Employee Number: " + emp2.empNum);
System.out.println("Email Address: " + emp2.empEmailAddress);
System.out.println("Year of Birth: " + emp2.yearOfBirth);
}
}
You add a method called print to the employee class called print
class Employee1{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
public void print() {
System.out.println("Employee name:" + empName);
System.out.println("Employee number:" + empNum);
// etc
}
}
and call it like this:
// these lines replace the System.out.println block in your code
emp1.print();
emp2.print();
class Employee1
{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
#Override toString(){
System.out.println(empName + empNum + empEmailAddress + yearOfBirth);
}
}
emp.toString();
You can override toString() method in class Employee like this
class Employee1{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
#Override
public String toString(){
return empName + emNum +.....
}
}
And use this to print in EmployeeTest sysout(instanceOfEmployee)

Trouble with inner class, toString confliction

Based on one of the Head First books examples I'm having a little trouble in which the toString method is causing issues with my student and they're uni and home address being outputted correctly. All i'm trying to do is output if a students uni address is empty use his home address else use the uni one.
But my test data looks like the following
John John72 Nottingham Drive
John72 Nottingham Drive
public class Test {
public static void main(String[] args){
Student student1 = new Student("John", 19, "Walkers Way");
student1.setUniAddress(72, "Nottingham Drive");
System.out.print(student1.toString());
}
}
Other Class
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet){
this.name = name;
this.homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() { return this.name; }
public Address getHomeAddress(){
if(this.uniAddress == null){
return this.homeAddress;
}else{
return getUniAddress();//this.uniAddress;
}
}
public Address getUniAddress() { return this.uniAddress; }
public void setUniAddress(int number, String add){
Address address = new Address(number, add);
uniAddress = address;
}
#Override
public String toString(){
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
}
public class Address{
private int number;
private String street;
public Address(int no, String street){
this.number = no;
this.street = street;
}
#Override
public String toString(){
return name + number + " " + street + "\n";
}
}
}
Your getHomeAddress method takes care of displaying the uni address, so this line:
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
can be shortened to:
return getName() + " " + getHomeAddress() + " " + "\n";
Otherwise your getHomeAddress method will pull the uni address, then your getUniAddress method will pull the uni address again.
Also in your address toString you are pulling the person's name and you probably didn't mean to (and you might not want a newline here either since you have a newline in your other toString method).
#Override
public String toString(){
return number + " " + street;
}

Categories