Checking if an object is in arraylist in Java - java

So here is assignment :
A student entity has a name and an address (both represented by an object of class Name and Address), in addition to a university ID, and a course schedule represented by an ArrayList of Courses
Your code should not allow the creation of Two students with the same university ID
So I'm thinking of using ArrayList to hold a list of student and check if student exists or not before create a new student. sorry, this is my first question so I'm trying my best to explain it:
This is my Address class:
public class Address {
private int streetNumber;
private String streetName;
private String city;
private String state;
private int province;
private String country;
public Address (int streetNumber,String streetName,String city,String state,int province,String country)
{
this.streetNumber=streetNumber;
this.streetName=streetName;
this.city=city;
this.state=state;
this.province=province;
this.country=country;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return " [streetNumber=" + streetNumber + ", streetName=" + streetName
+ ", city=" + city + ", state=" + state + ", province="+province+", country="
+ country + "]";
}
public boolean equals(Address add)
{
if(add==null)
{
return true;
}
if(this.getClass()!=add.getClass())
{
return false;
}
Address address=(Address) add;
return streetNumber==address.streetNumber &&
province==address.province && streetName.equals(address.streetName)
&& city.equals(address.city)&& state.equals(address.state)&& country.equals(address.country);
}
}
This is my Name class
public class Name {
private String firstName;
private String lastName;
private char middle;
public Name (String fiName,String laName, char middle)
{
this.firstName=fiName;
this.lastName=laName;
this.middle=middle;
}
public String getFirst()
{
return firstName;
}
public void setFirst(String first)
{
firstName=first;
}
public String getLast()
{
return lastName;
}
public void setLast(String last)
{
lastName=last;
}
public char getMiddle()
{
return middle;
}
public void setMiddle(char midd)
{
middle=midd;
}
/*public String toString()
{
return "[First Name= "+ firstName +" Last Name "+ lastName+" Middle Name "+ middle +"";
}*/
}
This is my Student class:
public class Student {
private int studentId;
private Name name;
private Address address;
boolean a;
ArrayList<Course> courseSchedule = new ArrayList<Course>();
ArrayList<Student> student=new ArrayList<Student>();
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(student.contains(id))
{
System.out.println("Student cannot be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
student.add();
}
}
public int getID()
{
return studentId;
}
public void setId(int id)
{
this.studentId = id;
}
public ArrayList<Course> getCourseSchedule()
{
return courseSchedule;
}
public void setCourseSchedule(ArrayList<Course> courseSchedule)
{
this.courseSchedule = courseSchedule;
}
public void addCourse(Course c) {
courseSchedule.add(c);
}
public void dropCourse(Course course) {
courseSchedule.remove(course);
}
}
My question is how can you add Student Object into Student ArrayList
and how can I check if the Student Id exists in ArrayList with contains() method
student.contains(id) this line right here it does not seem to be right
I hope im explain my question a little clear now. Sorry for my english also.

You would not keep a list of Student objects within the class for Student. Your ArrayList<Student> student=new ArrayList<Student>(); does not belong there.
You would have another structure or collection kept elsewhere named something like StudentBody. When a student is instantiated, it is added to the StudentBody collection.
List< Student > studentBody = new ArrayList< Student >() ; // This list is stored somewhere else in your app.
You could loop a List of Student objects in the StudentBody object. For each you would access the UniversityId member field and compare to your new one being added.
Or you could use a Map, where the key is a UniversityId object and the value is a Student object. Check for an existing key before adding.
These solutions ignore the important issue of concurrency. But that is likely okay for a homework assignment in a beginning course in programming.

Use A HashMap() for collecting information based on unique Ids.
public class Student {
private int studentId;
private Name name;
private Address address;
private static HashMap<Integer,Student> students = new ConcurrentHashMap<>(); // Make a static Map so all objectrs shared same data
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(students.contains(id))
{
System.out.println("Student can be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
students.put(id,this); // use this to add current object
}
}

Related

How to output complete details

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

Unable to print out the desired output

So I am creating a program that reads customer details and order details from two different files. I created methods to read the file, store the data in the object of customers and then add the object of customers into linkedlist.. Now when I try doing the same for order file, I am getting the wrong output. so in the code shown below, I am trying to check if the customer name entered in order file matches the name stored in customer linkedlist.. So say I have two rows in the order.txt file:
Ord101 true James
Ord102 false Jim
with what I have done, I get the following output:
Ord102 false Jim
Ord102 false Jim
instead of getting the correct output which would be:
Ord101 true James
Ord102 false Jim
because both, James and Jim are names present in Customer file and linkedlist. So here is my code for reading order file:
public void readFileOrder() {
Scanner y;
String b,c,d;
LinkedList<Customers> list=new LinkedList<Customers>(); //another method was already created to add data inside list and its working so list contains data
LinkedList<order> list1=new LinkedList<order>();
Boolean isOpen;
order Order1=new order();
while(y.hasNext())
{
b=y.next();
isOpen=y.nextBoolean();
d=y.next();
System.out.println(list);
Customers customers1=new Customers();
for(int i=0;i<list.size();i++) //this is where i'm checking if the customer name in the order file matches the value in list
{
if(list.get(i).getName().equals(d))
{
customers1=list.get(i);
Order1.setCustomer(customers1);
Order1.setName(b);
Order1.setIsOpen(isOpen);
list1.add(Order1);
}
}
}
for(int j=0;j<list1.size();j++)
{
System.out.println(list1.get(j).getCustomer()+" and "+list1.get(j).getName()+" and "+list1.get(j).getIsOpen());
}
}
just in case, provided below are Customer and order class:
import java.util.LinkedList;
public class Customers {
#Override
public String toString() {
return "Customers [Name=" + Name + ", age=" + age + ", email=" + email + ", Address=" + Address + "]";
}
String Name;
int age;
String email;
String Address;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public void removeCustomer(String name2, LinkedList<Customers> list) {
for(int k=0;k<list.size();k++)
{
if(list.get(k).getName().equals(name2))
{
list.remove(list.get(k));
}
}
}
}
order class:
import java.util.LinkedList;
public class order{
String name;
Boolean isOpen;
Customers customer;
String cusName;
public order() {
super();
}
public String getName() {
return name;
}
public order(Customers customer) {
super();
this.customer = customer;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsOpen() {
return isOpen;
}
public void setIsOpen(Boolean isOpen) {
this.isOpen = isOpen;
}
public String getCustomer() {
return customer.getName();
}
public void setCustomer(Customers customer) {
this.customer=customer;
this.cusName=customer.getName();
}
}
You are adding references to the same order to the list over and over again, each time overwriting the attributes set in the previous iteration of the loop. Instead, create a new order inside the loop.
In other words, change this:
order Order1=new order();
while(y.hasNext()) {
to this:
while(y.hasNext()) {
order Order1=new order();

How can I remove items from arrayList by StudentID?

I need to write a method that removes students from the ArrayList (myRoster) by student ID. If the student ID doesn't exist, the method should print an error message indicating that it is not found. I have written a remove method where I'm able to remove item by index. The error message 'Student with ID 3 was not found' is returning 6 times (3 from first remove and 3 from second error message). But I want to get one error message for second remove method which I'm calling in main method. A little help would be much appreciated.
Student Class
public class Student {
private int StudentID;
private String FirstName;
private String LastName;
private String Email;
private int age;
private int[] Grades;
//Constructor
public Student(int S_ID,String fName,String lName,String email,int Age,
int[] grade){
setStudentID(S_ID);
setFirstName(fName);
setLastName(lName);
setEmail(email);
setAge(Age);
setGrade(grade);
}
//Accessor Methods (get methods)
public int getStudentID(){
return StudentID;
}
public String getFirstName(){
return FirstName;
}
public String getLastName(){
return LastName;
}
public String getEmail(){
return Email;
}
public int getAge(){
return age;
}
public int[] getGrades(){
return Grades;
}
//Mutator methods (set methods)
public void setStudentID(int StudentID){
this.StudentID=StudentID;
}
public void setFirstName(String FirstName){
this.FirstName=FirstName;
}
public void setLastName(String LastName){
this.LastName=LastName;
}
public void setEmail(String Email){
this.Email=Email;
}
public void setAge(int age){
this.age=age;
}
public void setGrade(int Grade[]){
this.Grades=Grade;
}
}
Roster Class
import java.util.ArrayList;
public class Roster {
private static ArrayList<Student> myRoster= new ArrayList<>();
public static void main(String[] args) {
add(1,"John", "Smith", "John1989#gmail.com", 20, 88,79, 59);
add(2,"Suzan", "Erickson", "Erickson_1990#gmailcom",19,91,72,85);
add(3,"Jack","Napoli","The_lawyer99yahoo.com",19,85,84,87);
add(4,"Erin", "Black","Erin.black#comcast.net",22,91,98,82 );
add(5,"Henry","Adam","adam1#gmail.com",25,85,84,79);
remove(3);
remove(3);//expected: This should print a message saying such a student with this ID was not found
}
public static void add(int S_ID,String fName,String lName,String email,int
Age, int grade1, int grade2, int grade3){
int[] Grades={grade1, grade2,grade3};
Student newStudent= new Student(S_ID, fName, lName, email, Age, Grades);
myRoster.add(newStudent);
}
public static void remove(int StudentID){
for (int i = 0; i < myRoster.size(); i++){
if(i == StudentID){
myRoster.remove(i);
}else{
System.out.println("Student with ID "+StudentID+" was not found");
}
}
}
}
}
You should never attempt to remove an element from a list while iterating over it.
Your comparison is incorrect, reason being that you're comparing the for loop control variable i with the parameter StudentID rather it should be if(myRoster.get(i).getStudentID == StudentID).
The reasoning as to why the text "Student with ID "+StudentID+" was not found" is being printed to the console multiple times is because you've inserted it inside the loop, meaning each time the parameter StudentID doesn't match the value that it's being compared to, it will print the same message...
To accomplish your task you can simply use the ArrayList#removeIf method to remove the Student with the specified StudentID, else if the ArrayList#removeIf returns false then you can print the appropriate message as shown within the solution below.
public static void remove(int StudentID) {
if (!myRoster.removeIf(s -> s.getStudentId() == StudentID))
System.out.println("Student with ID " + StudentID + " was not found");
}
Your remove method is currently giving the error message once for every student in the list that doesn't have the desired student ID.
for (int i=0;i<myRoster.size();i++){
if(i==StudentID){
myRoster.remove(i);
}else{
System.out.println("Student with ID "+StudentID+" was not found"); }
That print statement is called any time the student at index i does not have the desired ID, not when there are no students that have that ID.
An easy way to fix this would be to put a boolean at the start of the method and set it to false. Then, in the if (i == StudentID) block, remove the student and set the value to true. Then, after the loop is complete, check if the boolean is true; if it is true, then the desired student has been removed. If it is still false, then there is no student with the desired ID.
It should look something like this:
public static void remove(int studentID) {
boolean studentFound = false;
for (int i=0;i<myRoster.size();i++){
if(i==StudentID){
myRoster.remove(i);
i--; // you have to decrement this value to account for the missing item
studentFound = true; // student with desired ID is removed
}
if (!studentFound) System.out.println("Student with ID "+StudentID+" was not found");
}
You problem seems to be that your loop in the remove() method isn't looping over studentIDs but just the looping index. You should loop over studentIDs. Your code prints each time an ID doesn't match the given ID. That's why you get multiple print messages. You should instead only print if no one matches (i.e. roster size doesn't change).
public static void remove(int StudentID){
int initialSize = myRoster.size(); //store initial size of roster to check if it changes
for (int i=0;i<myRoster.size();i++){
if(myRoster.get(i).getStudentID == StudentID){
myRoster.remove(i);
}
}
//checks if a student was removed which means the ID was found.
if(initialSize == myRoster.size()){
System.out.println("Student with ID "+StudentID+" was not found");
}
}
You can use Iterator interface as well for your purpose as shown below.
public static void remove(int StudentID) {
Iterator<Student> it = myRoster.iterator();
while(it.hasNext()) {
Student stud = (Student)it.next();
if (stud.getStudentID() == StudentID) {
it.remove();
return;
}
}
System.out.println("Student with ID " + StudentID + " was not found");
}
Yes you can do this ,please some add things in your Student class
public class Student {
private int StudentID;
private String FirstName;
private String LastName;
private String Email;
private int age;
private int[] Grades;
public Student(int S_ID ){
this.setStudentID(S_ID);
}
//Constructor
public Student(int S_ID,String fName,String lName,String email,int Age,
int[] grade){
setStudentID(S_ID);
setFirstName(fName);
setLastName(lName);
setEmail(email);
setAge(Age);
setGrade(grade);
}
//Accessor Methods (get methods)
public int getStudentID(){
return StudentID;
}
public String getFirstName(){
return FirstName;
}
public String getLastName(){
return LastName;
}
public String getEmail(){
return Email;
}
public int getAge(){
return age;
}
public int[] getGrades(){
return Grades;
}
//Mutator methods (set methods)
public void setStudentID(int StudentID){
this.StudentID=StudentID;
}
public void setFirstName(String FirstName){
this.FirstName=FirstName;
}
public void setLastName(String LastName){
this.LastName=LastName;
}
public void setEmail(String Email){
this.Email=Email;
}
public void setAge(int age){
this.age=age;
}
public void setGrade(int Grade[]){
this.Grades=Grade;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return StudentID == student.StudentID;
}
#Override
public int hashCode() {
return StudentID;
}
}
and in main area class you can do
public class Test {
public static void main(String []args){
List<Student> list = new ArrayList<>();
list.add(new Student(1,"a","a","a",1, new int[]{1}));
list.add(new Student(2,"b","b","b",2, new int[]{2}));
list.remove(new Student(1));
list.forEach(System.out::println);
}
}
Output
com.traveliko.platform.web.frontend.Student#2

My toString() is returning only one object times the number of the total object

Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?

java toString() is returning null from class [closed]

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();
}

Categories