So, I have three classes where the Class1 is used for different objects. In main class, the Class1 objects are made and names are set. Main class also makes new Household objects, the names are given to households and finally, persons are added to households as follows:
HouseholdOne.addPeopleToHousehold(person1);
The main class does not concern in present problem.
public class Class1 {
private String firstName;
private String middleName;
private String lastName;
public String setFirstName(String firstName) {
return this.firstName = firstName;
}
public String setLastName(String lastName) {
return this.lastName = lastName;
}
public String setMiddleName(String middleName) {
return this.middleName = middleName;
}
public String toString() {
if(firstName == "" && middleName == "" && lastName == "") {
return "";
} else if (firstName == null && middleName == null && lastName == null) {
return null;
} else
return firstName + " \"" + middleName + "\" " + lastName;
}
}
In the second class Household "addPeopleToHousehold" method the middle name of person should be parsed out from parameter and added to people list.
I had in mind to use .split function, but it does not work with object parameter.
How can I get given person middle name and
peopleList.add(personMiddleName)
Also in Household class, toString should print out household members like:
member1, member2, ... , memberx
public class Household {
List<Class1> peopleList = new ArrayList<>();
public String householdName;
public String setHouseholdName(String householdName) {
return this.householdName = householdName;
}
public void addPeopleToHousehold(Class1 people) {
// implementation needed //
}
public int getNumberOfPeople() {
return people.size();
}
public String toString() {
if (householdName == null || householdName == "") {
return "" + people;
}
return householdName + ": " + people;
}
}
Something like this perhaps? It was difficult to decipher your post, but the signature from the various methods says a lot. My changes simply adds people do the ArrayList peopleList. When you print the Household it will first check if a valid household name exists, after that it will loop each individual in the Household and add their full name to the list. The ((i + 1) != peopleList.size()) is only used to separate the names with a , except the last name.
Updated Class1. Fixed the setters and added a public getter for middle name.
public class Class1 {
private String firstName;
private String middleName;
private String lastName;
/*
* Setters
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
/*
* Getters
*/
public String getMiddleName() {
return middleName;
}
/*
* toString
*/
public String toString() {
if(firstName == "" && middleName == "" && lastName == "") {
return "";
} else if (firstName == null && middleName == null && lastName == null) {
return null;
} else
return firstName + " \"" + middleName + "\" " + lastName;
}
}
Updated Household class. Various fixes:
public class Household {
List<Class1> peopleList = new ArrayList<>();
public String householdName;
public String setHouseholdName(String householdName) {
this.householdName = householdName;
}
public void addPeopleToHousehold(Class1 people) {
peopleList.add(people);
}
public int getNumberOfPeople() {
return peopleList.size();
}
public String toString() {
String returnString = "";
if (householdName != null) {
returnString = householdName + ": ";
}
// Loop the members
for (int i = 0; i < peopleList.size(); i++) {
returnString += peopleList.get(i).getMiddleName();
if ((i + 1) != peopleList.size()) {
returnString += ", ";
}
}
return returnString;
}
}
In addition to the answer of OptimusCrime, you might want to use StringBuilder instead of just using returnString += to append strings.
The drawback of using += to append strings is it will create new String objects whenever you append, so you will have greater memory consumption.
Related
I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class
I've just learned about superclasses and subclasses and the homework is pretty simple: have 2 classes and a test class to call and print the attributes. Below is my code from all 3 classes. My question is, why isn't the department attributes printing in my main? Everything else prints just fine, I just can't get that last little bit to print. I think it has something to do with super...thank you in advance! Second computer course and I'm finally feeling I sort of get it, so that's improvement from the first class I took!
public class Employee {
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee () {
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.00;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getEmployeeID() {
return employeeID;
}
public double getSalary() {
return salary;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " + getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
return employeeSummary;
}
}
public class Manager extends Employee {
private String departmentA;
public Manager() {
super();
departmentA = null;
}
public String getDepartmentA() {
return departmentA;
}
public void setDepartmentA(String departmentA) {
this.departmentA = departmentA;
}
public void EmployeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
}
public class ManagerDerivation {
public static void main(String[] args) {
Manager person = new Manager();
person.setFirstName("Ron");
person.setLastName("Weasley");
person.setEmployeeID(2345);
person.setSalary(65000.00);
person.setDepartmentA("Department of Magical Law Enforcement");
person.employeeSummary();
return;
}
}
Method names are case sensitive. EmployeeSummary() does not override employeeSummary() because it uses a different name.
To avoid mistakes like this, always include the #Override annotation on overridden methods. If you include that annotation and make a mistake in the method signature, compilation will fail.
Note also that your return types for the two methods are different (String and void). Overridden methods must have compatible return types.
There is some spelling (employeeSummary vs. EmployeeSummary) mistakes and return types dont match, in Employee should be
public void employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " +
getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
}
then in Manager
public void employeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Since I've finished my code I am debugging every step in the main. I keep hitting a NullPointerException not even 40 lines in. The problem is my setter is not working in my Person class. Or what I assume that my setter isn't working. But I also first believe my read isn't working for my file.
I've tried to change around the variables but I simply can't find the problem and why it won't add the name to the Person class. I read into NullPointerExceptions on here and can't find where that problem is for me to fix in my code.
public class Person {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
public Person(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
protected Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#Override
public String toString() {
return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
}
public String toCSV() {
return this.firstName + "," + this.lastName + "," + this.address + "," + this.city
+ "," + this.state + "," + this.zipCode;
}
public void copy(Person p) {
firstName = p.firstName;
lastName = p.lastName;
address = p.address;
city = p.city;
state = p.state;
zipCode = p.zipCode;
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public Person clone() {
Person p = new Person(this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode);
return p;
}
}
public class Customer extends Person{
private int customerID;
private double grossSales;
public Customer(int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
this.customerID = customerID;
this.grossSales = grossSales;
}
public Customer(String s, int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
copyCSV(s);
}
protected Customer() {
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public double getGrossSales() {
return grossSales;
}
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
#Override
public String toString() {
return "CustomerID: " + customerID + "\nGrossSales: " + grossSales + super.toString();
}
public String toCSV() {
return this.customerID + "," + this.grossSales + "," + super.toCSV();
}
public void copy(Customer c) {
super.copy(c);
customerID = c.customerID;
grossSales = c.grossSales;
}
public void copy(int customerId, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super.copy(firstName, lastName, address, city, state, zipCode);
this.customerID = customerId;
this.grossSales = grossSales;
}
public Customer clone() {
Customer c = new Customer(this.customerID, this.grossSales, this.getFirstName(), this.getLastName(), this.getAddress(), this.getCity(), this.getState(), this.getZipCode());
return c;
}
public int compareTo(Customer c) {
int returnValue = 0;
if (this.customerID > c.customerID) {
returnValue = -1;
} else if (this.customerID < c.customerID) {
returnValue = 1;
} else {
returnValue = 0;
}
return returnValue;
}
public void copyCSV(String s) {
List<String> list = new ArrayList<>();
String[] a = s.split(",");
list = Arrays.asList(a);
this.copy(Integer.parseInt(list.get(0)), Double.parseDouble(list.get(1)), list.get(2),
list.get(3), list.get(4), list.get(5), list.get(6), list.get(7));
}
}
public class CustomerList {
public Customer[] cl;
public int size;
public CustomerList() {
this.cl = new Customer[4];
}
public int size() {
return this.size = cl.length;
}
public Customer get(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
return cl[i];
}
public boolean set(Customer c,Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
} else {
cl[i] = c;
return true;
}
}
public void add(Customer c) {
for (int i = 0; i < size; i++) {
if (cl[i] == null) {
cl[i] = c;
} else {
if (i == size) {
Customer[] temp = new Customer[size * 2];
for (int j = 0; j < size; j++) {
temp[j] = cl[j];
}
cl[size] = c;
size++;
}
}
}
}
public Customer remove(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
Customer temp = cl[i];
for (int j = 0; j < cl.length - 1; j++) {
cl[i] = cl[i + 1];
}
return temp;
}
#Override
public String toString() {
String s = " ";
double sum = 0;
for(Customer c: cl){
if(c == null)
s = "";
else
s += c + " \n";
}
for(Customer c: cl){
if (c == null)
sum += 0;
else
sum += c.getGrossSales();
}
return s + "\n" + "Total Gross Sales = " + Double.toString(sum);
}
public static CustomerList read(String fn) throws FileNotFoundException {
Scanner input = new Scanner(new File(fn));
CustomerList ab = new CustomerList();
try {
while(input.hasNextLine()) {
String currentline = input.nextLine();
Customer cd = new Customer();
cd.copyCSV(currentline);
cd.toCSV();
ab.add(cd);
}
} finally {
return ab;
}
}
//Write is facing the same problems as read. We can't access the toCSV() method from Customer.
public static boolean write(CustomerList cl, String fn) throws FileNotFoundException {
boolean a = false;
PrintWriter output = new PrintWriter(new File(fn));
// try {
for (int i = 0; i < cl.size; i++) {
Customer cd = new Customer();
cd.toCSV();
// }
// } catch (FileNotFoundException s) {
// System.out.println("File does not exist please try again: ");
// return a;
} return a = true;
}
//I utilized the sort function it said to and assume this will work as expected.
public void sort() {
Arrays.sort(cl);
}
public int indexOf(int id) {
for (int i = 0; i < size; i++) {
if(cl[i].getCustomerID() == id) {
return i;
}
}
return -1;
}
public boolean update(int id, double amt) {
boolean test;
int index = indexOf(id);
if(index == -1) {
System.out.println("CustomerID not present");
test = false;
} else {
amt += cl[index].getGrossSales();
test = true;
}
return test;
}
}
public static void main(String[] args) throws FileNotFoundException {
boolean b = false;
// Read file
System.out.println("Read file");
CustomerList cl = CustomerList.read("Customers.csv");
if(cl != null) {
System.out.println("Read: " + cl.size() + " records");
System.out.println(cl.toString() + "\n\n\n");
} else {
System.out.println("File read error.");
return;
}
// Test get and set for CustomerList
System.out.println("Test get and set for CustomerList");
System.out.println("x = " + cl.get(0));
Customer c = cl.get(0);
c.setFirstName("Homer"); // This is the line it keeps stopping at.
cl.set(c, 0);
System.out.println("x = " + cl.get(0));
System.out.println("\n\n\n");
It should be setting the first name of the customer as "Homer"
The only results it prints out is
Read file
Read: 4 records
Total Gross Sales = 0.0
Test get and set for CustomerList
x = null
--- Exception in thread "main" java.lang.NullPointerException
It's pretty simple, you ask to print cl.get(0). it returns null then you say Customer c = cl.get(0) which is null then you try to do c.setFirstName but c is null so nullPointerException.
Your are trying to access c but c is null. you need to initialize it as a new customer or make it equal to an actual customer (not null) before being able to setFirstName. Just do :
Customer c = new Customer();
c.setFirstName("homer");
It would work if your cl was not empty. To avoid this type of error you could also do :
Customer c;
if (cl.get(0) != null){
c = cl.get(0)
} else {
c = new Customer();
}
c.setFirstName("homer");
I am implementing a simple sorting class, and was wondering how I would implement this using a while loop rather than a do-while loop.
The outer loop is executed once for each item in the ‘names’ list. However, it’s a do-while loop, which is always executed at least once. This will lead to an incorrect result if ‘names’ is the empty list. It should be replaced with a while loop.
SORT CLASS
public class Sort {
public static ArrayList<Name> sort1(ArrayList<Name> names) {
ArrayList<Name> results;
results = new ArrayList<Name>();
int count = names.size();
do {
Name firstName = new Name("zzz", "zzz");
for (Name name : names) {
if (name.getFirstName().compareTo(firstName.getFirstName()) < 0
|| name.getFirstName().equals(firstName.getFirstName())
&& name.getSurName().compareTo(firstName.getSurName()) < 0) {
firstName = new Name(name.getFirstName(), name.getSurName());
}
}
results.add(firstName);
names.remove(firstName);
count--;
} while (count > 0);
return results;
}}}
NAME CLASS
class Name {
String firstName;
String surName;
public Name() {
}
public Name(String firstName, String surName) {
this.firstName = firstName;
this.surName = surName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String toString() {
return firstName + " " + surName;
}
public boolean equals(Object other) {
String fname = ((Name) other).firstName;
String sname = ((Name) other).surName;
if (firstName.equals(fname) && surName.equals(sname)) {
return true;
} else {
return false;
}
}
Just replace the do with your while (count > 0).
public class Sort {
private static void doIterate(List<Name> names, List<Name> results) {
Name firstName = new Name("zzz", "zzz");
for (Name name : names) {
if (name.getFirstName().compareTo(firstName.getFirstName()) < 0
|| name.getFirstName().equals(firstName.getFirstName())
&& name.getSurName().compareTo(firstName.getSurName()) < 0) {
firstName = new Name(name.getFirstName(), name.getSurName());
}
}
results.add(firstName);
names.remove(firstName);
}
public static ArrayList<Name> sort1(ArrayList<Name> names) {
ArrayList<Name> results;
results = new ArrayList<Name>();
int count = names.size();
doIterate(names, results);
count--;
while (count > 0) {
doIterate(names, results);
count--;
}
return results;
}}}
Since the while loop is always executed once, I would do a check prior to the loop to see if names has values in it. If yes, then do the do/while loop. Otherwise, skip it.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is Java, using BlueJ.
I have four classes called Person, Letter, Address and PhoneNumber. In each, I override the toString() method to return a concatenated string of the values I want from the class. When calling the Letter toString(), it is returning null on all values.
The idea is to use the hard coded information, pass it into the appropriate class, and return it in a standard letter format.
Am I headed in the right direction for printing out the information hard coded, or should I go a different route? This is a homework problem, but I feel I have hit a brick wall.
Here are the classes:
public class Person
{
private static String aPerson;
private String first;
private String middle;
private String last;
private Address address;
private PhoneNumber phone;
public String getFirst()
{
return this.first;
}
public void setFirst(String FirstName)
{
this.first = FirstName;
}
public String getMiddle()
{
return this.middle;
}
public void setMiddle(String MiddleName)
{
this.middle = MiddleName;
}
public String getLast()
{
return this.last;
}
public void setLast(String LastName)
{
this.last = LastName;
}
public Address getMyAddress()
{
return this.address;
}
public void setMyAddress(Address Address)
{
this.address = Address;
}
public PhoneNumber getMyPhoneNum()
{
return this.phone;
}
public void setMyPhoneNum(PhoneNumber Number)
{
this.phone = Number;
}
public Person()
{
aPerson = getFirst() + getMiddle() + getLast() + getMyAddress() +
getMyPhoneNum();
}
public String toString()
{
return aPerson;
}
}
PhoneNumber:
public class PhoneNumber
{
private String number;
private int areaCode = 0;
private int phonePrefix = 0;
private int phoneLineNum = 0;
private int phoneExtension = 0;
public String getNumber()
{
return number;
}
public void setNumber(String Number)
{
number = Number;
}
public int getAreaCode()
{
return areaCode;
}
public void setAreaCode(int AreaCode)
{
areaCode = AreaCode;
}
public int getPrefix()
{
return phonePrefix;
}
public void setPrefix(int Prefix)
{
phonePrefix = Prefix;
}
public int getPhoneLineNumber()
{
return phoneLineNum;
}
public void setLineNum(int PhoneNumber)
{
phoneLineNum = PhoneNumber;
}
public int getExtension()
{
return phoneExtension;
}
public void setExtension(int Extension)
{
phoneExtension = Extension;
}
}
Address:
public class Address
{
private String state;
private String anAddress;
private String address;
private String city;
private int zip = 0;
public String getState()
{
return state;
}
public void setState(String State)
{
state = State;
}
public String getAddress()
{
return address;
}
public void setAddress(String Address)
{
address = Address;
}
public String getCity()
{
return city;
}
public void setCity(String City)
{
city = City;
}
public int getZip()
{
return zip;
}
public void setZip(int Zip)
{
zip = Zip;
}
public Address()
{
anAddress = getState() + getAddress() + getCity() + getZip();
}
public String toString()
{
return this.anAddress;
}
}
Letter:
public class Letter
{
private Person to;
private Person from;
private String body;
private String finishedLetter;
public Person getTo()
{
return to;
}
public void setTo(Person newValue)
{
to = newValue;
}
public Person getFrom()
{
return from;
}
public void setFrom(Person newValue)
{
from = newValue;
}
public String getBody()
{
return body;
}
public void setBody(String newValue)
{
body = newValue;
}
public Letter()
{
finishedLetter = getTo() + " \n" + getFrom() + " \n" + getBody();
}
public String toString()
{
return finishedLetter;
}
}
And main:
public class MainClass
{
public static void main(String args[])
{
PhoneNumber phone1 = new PhoneNumber();
phone1.setAreaCode(417);
phone1.setPrefix(447);
phone1.setLineNum(7533);
phone1.setExtension(0);
PhoneNumber phone2 = new PhoneNumber();
phone2.setAreaCode(210);
phone2.setPrefix(336);
phone2.setLineNum(4343);
phone2.setExtension(9850);
Address address1 = new Address();
address1.setState("MO");
address1.setAddress("1001 East Chestnut Expressway");
address1.setCity("Springfield");
address1.setZip(65807);
Address address2 = new Address();
address2.setState("TX");
address2.setAddress("4800 Calhoun Road");
address2.setCity("Houston");
address2.setZip(77004);
Person person1 = new Person();
person1.setFirst("Shane");
person1.setMiddle("Carroll");
person1.setLast("May");
person1.setMyAddress(address1);
person1.setMyPhoneNum(phone1);
Person person2 = new Person();
person2.setFirst("Ted");
person2.setMiddle("Anthony");
person2.setLast("Nugent");
person2.setMyAddress(address2);
person2.setMyPhoneNum(phone2);
Letter aLetter = new Letter();
aLetter.setTo(person2);
aLetter.setFrom(person1);
aLetter.setBody("This is the body");
System.out.println(aLetter.toString());
}
}
Your Letter constructor is calling methods such as getTo() and getFrom() before those fields have been filled. Don't do this since your finishedLetter String will never be correctly "finished". i.e.,
public Letter()
{
finishedLetter = getTo() + " \n" + getFrom() + " \n" + getBody();
}
will always result in null + "\n" + null + "\n" + null
Perhaps that sort of code should be in the toString() method instead.
When your letter is constructed using new Letter(), it initializes its instance field finishedLetter with several null values. Because to, from, and body haven't yet been set with their corresponding setters, their getters return null, resulting in finishedLetter being equal to "null \nnull \nnull".
To fix this, I one approach is to define the finishedLetter in the toString() method itself. This will both fix the issue and take a more object-oriented approach to the program design.
// remove constructor (if you wish) and finishedLetter field
public String toString() {
return getTo() + " \n" + getFrom() + " \n" + getBody();
}
An even better approach is to require to, from, and body, as parameters in the Letter constructor.
// remove finishedLetter field
public Letter(Person to, Person from, String body) {
this.to = to;
this.from = from;
this.body = body;
}
public String toString() {
return getTo() + " \n" + getFrom() + " \n" + getBody();
}