How to store only multiple passengers inside the cabin class? - java

I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin should hold up to 3 passengers only. But I'm stuck on how to do this. I have created an array of cabin objects in my Ship.java class. I can only add one passenger into a cabin with below mentioned addCustomer method
Cabin[] cruiseShip = new Cabin[12];
for (int i = 0; i < cruiseShip.length; i++) {
cruiseShip[i] = new Cabin();
}
public static void addCustomer(Cabin[] cruiseShip, String firstName, String surName, int expenses, int cabinNumber){
if (cruiseShip[cabinNumber].getCabinName().equals("empty")){
cruiseShip[cabinNumber].setFirstName(firstName);
cruiseShip[cabinNumber].setSurName(surName);
cruiseShip[cabinNumber].setExpenses(expenses);
cruiseShip[cabinNumber].setCabinName("not empty");
System.out.println("Cabin number " + cruiseShip[cabinNumber].getCabinNumber() + " is occupied by " + cruiseShip[cabinNumber].getFirstName() + " " + cruiseShip[cabinNumber].getSurName() );
}
}
This is how Cabin.java looks :
public class Cabin extends Passenger {
int cabinNumber;
String cabinName;
public String getCabinName() {
return cabinName;
}
public void setCabinName(String cabinName) {
this.cabinName = cabinName;
}
public int getCabinNumber() {
return cabinNumber;
}
public void setCabinNumber(int cabinNumber) {
this.cabinNumber = cabinNumber;
}
}
This is how Passenger.java looks :
public class Passenger {
String firstName;
String surName;
int expenses;
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 int getExpenses() {
return expenses;
}
public void setExpenses(int expenses) {
this.expenses = expenses;
}
}

Cabin should contain a data-structure which holds passengers.(association 1-n, from 1_cabin-N_passengers) You could also restrict the no. of passengers regarding to cabin type (up to 2-3-n passengers) and also check not to add n-times the same passenger in the same cabin for a specific time. Same logic with Ship which have Cabins.
class Cabin
{
... etc ... as u did
List<Passenger> listP = new ArrayList<Passenger>();
}
listP.add(new Passenger(...));
class Ship
{
...
List<Cabin> listC = new ArrayList<Cabin>();
}
listC.add(new Cabin(...));
//get a specific cabin from the ship and add a new Passenger
//note maybe it's better to do your custom methods for add,get_Ship, Cabin (based on the requiremts).
//Standard List Methods usually do not fit exactly custom requirements, so need to be enhanced
ship.getlistC().get(i_specificCabin).listP.add(new Passenger(...));
Be carefully not to mix semantics, think how in real world things works (see #Jim Garrison).
Note: Maybe a Map<String/Integer,CustomObject> can fit well for ease of access based on key(id).

Your relationship become as per your code is 1 Cabin have multiple Passager so relationship is OneToMany. The best and easiest way to solve your problem is Composition in java. You are working with Inheritance, It has IS-A relationship but Compostion has HAS-A relationship. Composition is best to worked on relationship.
Here down is code that solved your problem using `Composition Technique:
Passenger.java
public class Passenger {
String firstName;
String surName;
int expenses;
// No argument constructor
public Passenger() {
}
// All argument constructor
public Passenger(String firstName, String surName, int expenses) {
this.firstName = firstName;
this.surName = surName;
this.expenses = expenses;
}
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 int getExpenses() {
return expenses;
}
public void setExpenses(int expenses) {
this.expenses = expenses;
}
}
Cabin.java
public class Cabin {
int cabinNumber;
String cabinName;
List<Passenger> passenger = new ArrayList<>();
// No argument constructor
public Cabin() {
}
// All argument constructor
public Cabin(int cabinNumber, String cabinName, List<Passenger> passenger) {
this.cabinNumber = cabinNumber;
this.cabinName = cabinName;
this.passenger = passenger;
}
public String getCabinName() {
return cabinName;
}
public void setCabinName(String cabinName) {
this.cabinName = cabinName;
}
public int getCabinNumber() {
return cabinNumber;
}
public void setCabinNumber(int cabinNumber) {
this.cabinNumber = cabinNumber;
}
public List<Passenger> getPassenger() {
return passenger;
}
public void setPassenger(List<Passenger> passenger) {
this.passenger = passenger;
}
}
Here down is Main class which insert record in Passanger and Cabin with relationship.
public static void main (String[] args) {
Cabin cabin = new Cabin();
// Insert and Put all Passanger in ArrayList
List<Passenger> passenger = new ArrayList<>();
passenger.add(new Passenger("Jack", "Crawly", 1000));
passenger.add(new Passenger("Michel", "Jordan", 2000));
passenger.add(new Passenger("Tim", "Leach", 3000));
if(cabin.getCabinName() == null)
{
// Insert Cabin with all Passenger
cabin = new Cabin(1, "Cabin1", passenger);
}
// Get all Passangers with Cabin
List<Passenger> passengers = cabin.getPassenger();
for (Passenger psg : passengers) {
System.out.println("Cabin Number : " + cabin.getCabinNumber());
System.out.println("FirstName : " + psg.getFirstName());
System.out.println("LastName : " + psg.getSurName());
System.out.println();
}
}

Related

How to give more than one role for an object in java?

the student and teacher class inherited from person class, because inheritance is not flexible the object will either be one of the two. to solve this i added an abstract class Role and make association between person and role and student and teacher inherits from Role class so that an instance can has a role of both student and teacher.The question is to make instance of the Teacher class can also be a student or a student also teaches how to test in the main class?
public class Person {
private int ssn;
private String name;
private List<PersonRole> roles;
public Person(int ssn, String name) {
this.ssn = ssn;
this.name = name;
roles = new ArrayList<PersonRole>();
}
public int getSsn() {
return ssn;
}
public String getName() {
return name;
}
}
/////////////// PersonRole /////////////////
public abstract class PersonRole {
private List<PersonRole> learning;
private List<PersonRole> teaching;
public PersonRole(List<PersonRole> learning, List<PersonRole> teaching) {
this.learning = learning;
this.teaching = teaching;
}
public List<PersonRole> getLearning() {
return learning;
}
public List<PersonRole> getTeaching() {
return teaching;
}
public void addAsStudent(PersonRole p) {
learning.add(p);
}
public void addAsTeacher(PersonRole p) {
learning.add(p);
}
}
///////////// Teacher //////////////
public class Teacher extends PersonRole {
private String faultyName;
private int yearsOfExperence;
public Teacher(String faultyName, int yearsOfExperence) {
super();
this.faultyName = faultyName;
this.yearsOfExperence = yearsOfExperence;
}
public String getFaultyName() {
return faultyName;
}
public int getYearsOfExperence() {
return yearsOfExperence;
}
}
/////////// Student ////////////////
public class Student extends PersonRole {
private String collegeName;
private String major;
public Student(String collegeName, String major) {
super();
this.collegeName = collegeName;
this.major = major;
}
public String getCollegeName() {
return collegeName;
}
public String getMajor() {
return major;
}
}
////// Main ///////////////
public class Main {
public static void main(String[] args) {
PersonRole p1 = new Student("univ of Michigan", "CS");
PersonRole p3 = new Student("Iowa state univ", "managemnt");
PersonRole p2 = new Teacher("computer science", 3);
PersonRole p4 = new Teacher("Management", 2);
Person person = new Person(1042327867, "Mike Rose");
person.addRole(p1);
person.addRole(p2);
person.addRole(p3);
person.addRole(p4);
for (PersonRole c: roles) {
System.out.println(c);
}
}
}
I would test it exactly as you would but the hierarchy of inheritance looks good. Why not give PersonRole a constructor and attributes so that the children can use super() in their constructors and reuse some code?
Try this to print your roles:
List<PersonRole> roles = person.getRole();
for(PersonRole role: roles) {
System.out.println(role);
}
Then add a toString method in the Student and Teacher classes:
public String toString() {
return "Student {" + "collegeName=" + collegeName + ", major=" + major + '}';
}
public String toString() {
return "Teacher {" + "faultyName=" + faultyName + ", yearsOfExperence=" + yearsOfExperence + '}';
}
The result will be this:
Student {collegeName=maharashi univ, major=compro}
Teacher {faultyName=computer science, yearsOfExperence=3}
Student {collegeName=Iowa state univ, major=managemnt}
Teacher {faultyName=Management, yearsOfExperence=2}

How to show that two children are siblings?

So I'm relatively new to the game. I have a java class "Family" in which I want to implement a boolean method that tells me whether x is the sibling of y (true or false) etc.
public class Family {
private final Gender gender; // enum
private final String name;
private Family parent;
private Family firstChild;
private Family seccondChild;
private Family thirdChild;
public Family (final String name, final Gender gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public Gender getGender() {
return gender;
}
public Family getThirdChild() {
return thirdChild;
}
public void setThirdChild(Family thirdChild) {
this.thirdChild = thirdChild;
}
public void setSeccondChild(Family seccondChild) {
this.seccondChild = seccondChild;
}
public Family getSeccondChild() {
return seccondChild;
}
public Family getFirstChild() {
return firstChild;
}
public void setFirstChild(Family firstChild) {
this.firstChild = firstChild;
}
public Family getParent() {
return parent;
}
public void setParent(Family parent) {
this.parent = parent;
}
// So here is my problem I don't know how to show, that two children are siblings or not
public boolean isTheSiblingOf(Family x) {
if ( ) { // If y is sibling of x return true.. How??
return true;
}
return false;
}
public String toString() {
return "Family: " + name;
}
}
Here is the other class for my objects. As you can see I only refered to the mother. I need the father for something else, but not now.
Family theo = new Family("Theo", Gender.M); // Father
Family clara = new Family ("Clara", Gender.F); // Mother
Family john = new Family("John", Gender.M);
john.setParent(clara); // I'm only choosing one parent
clara.setFirstChild(john);
Family rachel = new Family("Rachel", Gender.F);
rachel.setParent(clara);
clara.setSeccondChild(rachel);
Family jennifer = new Family("Jennifer", Gender.F);
jennifer.setParent(clara);
clara.setThirdChild(jennifer);
I know you are learning, but try thinking about how to better your code. You should create some type of class Person, which is gonna have attributes like parents, name & children. then just add them to your Family class.
public class Person {
private Person mother;
private Person father;
private String firstName;
private String lastName;
private List<Person> children = new ArrayList<Person>();
public Person(Person mother, Person father, String firstName, String lastName) {
this.mother = mother;
this.father = father;
this.firstame = firstName;
this.lastName = lastName;
}
void addChildren(Person child) {
children.add(child);
}
// GETERS AND SETTERS
}
public class Family {
private String familyName;
private List<Person> familyMembers = new ArrayList<Person>();
public Family(String name) {
this.familyName = name;
}
public boolean areSiblings(Person person1, Person person2) {
if(person1.getMother().equals(person2.getMother())
&& person1.getFather().equals(person2.getFather())) {
return true;
} else {
return false;
}
}
}

Send array data from one class to another JAVA

(I'm a beginner so this may sound obvious/lack information.) I have an ArrayList of attributes for different pets including attributes such as their given-name, common-name, the price of the animal, sex, date bought and date sold. this information is generated from a separate class that adds an array of information to an array of arrays of the already existing list of animals. Essentially, I want to send the array to another class (called Pets) so it can then be added to the array of arrays. I understand this may sound confusing but this is the only way I can word it, I can clarify anything if needed. Any help would be great as I'm really stuck and can't work out how to send it. This is the code that generates my values in the array (using text-boxes to input the information).
public void actionPerformed(ActionEvent e) {
ArrayList<String> NewanimalArr = new ArrayList<>();
String givenName = txtGivenname.getText();
String commonName = txtCommonName.getText();
String priceOf = txtPrice_1.getText();
String sexOf = txtSex.getText();
String colourOf = txtMaincolour.getText();
String dateOfA = txtArrivaldate.getText();
String dateSold = txtSellingdate.getText();
NewanimalArr.add(givenName);
NewanimalArr.add(commonName);
NewanimalArr.add(priceOf);
NewanimalArr.add(sexOf);
NewanimalArr.add(colourOf);
NewanimalArr.add(dateOfA);
NewanimalArr.add(dateSold);
System.out.println(NewanimalArr);
}
});
this will then print information generated that is entered for example:
[alex, Dog, 40.50, Male, Brown, 14/04/2015, 14/12/2016]
how do I then send this data to another class
Option one Constructor Injection:
public class Foo {
List<String> actionPerformed(ActionEvent e) {
List<String> newanimalArr = new ArrayList<>();
.....
return newanimalArr
}
...
public class Pets {
private final List<String> array;
public Pets(final List<String> array) {
this.array = array;
}
void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
Pets pets = new Pets(foo.actionPerformed( new ActionEvent() ) );
pets.bar();
}
Option two Getter-Setter Injection:
public class Foo {
private final List<String> newanimalArr;
public Foo() {
this.newanimalArr = new ArrayList<>();
}
public void actionPerformed(ActionEvent e) {
.....
}
public List<String> getNewanimalArr() {
return new ArrayList<String>(newanimalArr);
}
}
...
public class Pets {
private List<String> array;
public Pets() {
this.array = Collections.<String>emptyList();
}
public void setArray(final List<String> array) {
this.array = array;
}
public void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
foo.actionPerformed( new ActionEvent() );
Pets pets = new Pets();
bar.setArray( foo.getNewanimalArr() );
pets.bar();
}
See also Dependency Injection Patterns
Create a class definition of Pet, using instance variables for the fields. In Java it is custom to create a setXyz and a getXyz for each xyz field. You can also create a constructor in which you pass all the values and assign them to the fields, this minimizes the risk of fields not being filled in.
The initial ArrayList you are creating doesn't add that much use, it is easier to create the Pet instances directly:
List<Pet> newArrivals = new ArrayList<>();
// get data from view fields and if necessary transform them to other objects such as:
LocalDate arrivedOn = LocalDate.parse(txtArrivaldate.getText(), DateTimeFormatter.ofLocalizedDate(FormatStyle.FormatStyle);
// create and add a new Pet object to the list
newArrivals.add(new Pet(.....));
public class Pet {
public enum Gender {
FEMALE, MALE
}
private String givenName;
private String commonName;
private double price;
private Gender gender;
private String color;
private LocalDate arrivedOn;
private LocalDate soldOn;
public Pet() {
}
public Pet(String givenName, String commonName, double price, Gender gender, String color, LocalDate arrivedOn,
LocalDate soldOn) {
super();
this.givenName = givenName;
this.commonName = commonName;
this.price = price;
this.gender = gender;
this.color = color;
this.arrivedOn = arrivedOn;
this.soldOn = soldOn;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getCommonName() {
return commonName;
}
public void setCommonName(String commonName) {
this.commonName = commonName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public LocalDate getArrivedOn() {
return arrivedOn;
}
public void setArrivedOn(LocalDate arrivedOn) {
this.arrivedOn = arrivedOn;
}
public LocalDate getSoldOn() {
return soldOn;
}
public void setSoldOn(LocalDate soldOn) {
this.soldOn = soldOn;
}
}

Null values when printing out arrayList?

Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)

How to produce a functional LinkedList Class?

As part of an assignment I am having to produce a LinkedList class called Registry. It is intended to be part of a simple student registration system with an interface.
Unfortately, I have literally hit a wall and have no idea on what to do next with what I am doing here. The Registry class is just intended to manage a linked list of students called studentList.
Below is the current, rather incomplete class I have made so far.
import java.util.*;
public class Registry
{
LinkedList<Student> studentList;
public Registry()
{
}
public void addStudent(Student aStudent)
{
studentList.add(aStudent);
}
public void deleteStudent(int studentID)
{
studentList.remove(studentID);
}
#Override
public String toString()
{
return getClass().getName() +
}
public String format()
{
System.out.format(studentList);
}
}
Now, my main worry is using Student. As part of the assignment, I have had to make another class called Student which create instances of Students, containing forenames, surnames, Student IDs and degree Schemes as strings.
How will I be able to use that sperate class to be added to the LinkedList instanted in Registry? And how can I get the Registry class to fully function?
I will try and provide any additional details on request. I am likely unclear, so if I am, let me know, and I will try and explain as best I can.
EDIT: This is the Student Class as requested:
public class Student
{
private String foreName;
private String surName;
private String studentID;
private String degreeScheme;
public Student()
{
}
public void setForeName(String foreName)
{
this.foreName = foreName;
}
public String getForeName()
{
return foreName;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public String getSurName()
{
return surName;
}
public void setStudentID(String studentID)
{
this.studentID = studentID;
}
public String getStudentID()
{
return studentID;
}
public void setDegreeScheme(String degreeScheme)
{
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme()
{
return degreeScheme;
}
#Override
public String toString()
{
return getClass().getName() + "[foreName = " + foreName + " surName "
+ surName + " studentID " + studentID + " degreeScheme "
+ degreeScheme + "]";
}
public void format()
{
System.out.format("%5s%20s%11s%20s", foreName, surName, studentID, degreeScheme);
}
}
import java.util.Iterator;
import java.util.LinkedList;
public class Tester {
public static void main(String[] args) {
Registry r = new Registry();
r.addStudent(new Student("13", "John", "Doe", "Physics")); // Add a student to the Registry
r.addStudent(new Student("212", "Jane", "Bow", "Chem")); // Add another Student
System.out.println(r); // Print the Student List
r.deleteStudent(212); // Deletes student with ID 212
System.out.println(r);
}
}
class Student {
private String studentID;
private String foreName;
private String surName;
private String degreeScheme;
public Student(String studentId, String foreName, String surName, String degreeScheme) {
this.studentID = studentId;
this.foreName = foreName;
this.surName = surName;
this.degreeScheme = degreeScheme;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
public String getForeName() {
return foreName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getStudentID() {
return studentID;
}
public void setDegreeScheme(String degreeScheme) {
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme() {
return degreeScheme;
}
#Override
public String toString() {
return getClass().getName() + "[foreName = " + foreName + " surName " + surName + " studentID "
+ studentID + " degreeScheme " + degreeScheme + "]";
}
public void format() {
System.out.format("%5s%20s%11s%20s", foreName, surName, studentID, degreeScheme);
}
}
class Registry {
LinkedList<Student> studentList;
public Registry() { // Creates studentList
studentList = new LinkedList<>();
}
public void addStudent(Student aStudent) {
studentList.add(aStudent);
}
public void deleteStudent(int studentID) {
int index = searchList(studentID); // Gets index of the student in the Registry
if (index == -1)
throw new IllegalArgumentException("Student not found");
// Since studentList is implemented as LinkedList, .remove removes element at specified position
studentList.remove(index);
}
// Search by studentID , if found, return position in the list
private int searchList(int studentID) {
Iterator<Student> it = studentList.iterator();
int count = -1;
while (it.hasNext()) {
count++;
Student temp;
temp = it.next();
if (Integer.parseInt(temp.getStudentID()) == studentID) {
return count;
}
}
return -1;
}
#Override
//Suggestions to improve the toString are welcome
public String toString() {
for (Student student : studentList) {
student.format();
System.out.println();
}
return "";
}
}
In any data structure there are three functions that almost always require implementation:
Insertion
Searching
Deletion
Let me begin by clarifying what the general Linked List structure consists of.
The linked list works by operating on nodes. Each node contains the actual data you want to store/modify/access.
Registry: This should be responsible for maintaining the structure and providing a way of inserting/searching for/deleting specific nodes in the list.
Student: Stores the data and controls how it is accessed and modified
So far, you have your Registry framework created appropriately. (Although you will want to implement a search method.)
For your student class, you simply create the member variables of the class that you need, as well as the appropriate getters/setters for them.
public class Student {
private String id;
private String forename;
private String surname;
private String degreeScheme;
private Student next; // Maintains a reference to the next node in the list
Student () {
//Default constructor values
}
Student (String id, String forename, String surname, String degreeScheme, Student next) {
this.id = id;
this.forename = forename;
this.surname = surname;
this.degreeScheme = degreeScheme;
this.next = next;
}
public void setID (String id) {
this.id = id;
}
public String getID () {
return id;
}
public void setforename (String forename) {
this.forename = forename;
}
public String getforename () {
return forename;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname () {
return surname;
}
public void setDegreeScheme(String degreeScheme) {
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme () {
return degreeScheme;
}
public void setNext (Student next) {
this.next = next;
}
public Student getNext () {
return next;
}
} //End Student Class
This should be a good base to get you started. Remember, when creating data structures you'll avoid a lot of headaches by making sure that you have a clear separation of concerns. Make the student class purely responsible for storing and maintaining the data, and let the Registry class be responsible for maintaining the structure itself!
At this point, you can utilize the Student class within your Registry class, just insert the nodes as you want, search for them, delete them as needed.

Categories

Resources