Creating a genealogical tree java - java

I have the following structure:
Member {
String firstName;
String secondName;
Member[] children;
Member father;
}
I have to implement this tree in java;
I have a first name and a second name of a member. I need to find the way from root to that node.
Can someone help me, please?
This is what i have:
public class Member {
public List<Member> children = new ArrayList<>();
public Member father = null;
public String secondName = null;
public String firstName = null;
public Member(String secondName, String firstName) {
this.secondName = secondName;
this.firstName = firstName;
}
public Member(String secondName, String firstName, Member father) {
this.secondName = secondName;
this.firstName = firstName;
this.father = father;
}
public List<Member> getChildren() {
return children;
}
public void setFather(Member father) {
this.father = father;
father.addChild(this);
}
public void addChild(String secondName, String firstName) {
Member child = new Member(secondName, firstName);
child.setFather(this);
this.children.add(child);
}
public void addChild(Member child) {
child.setFather(this);
this.children.add(child);
}
public String getSecondName() {
return this.secondName;
}
public String getFirstName() {
return this.firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public void setPrenume(String firstName) {
this.firstName = firstName;
}
public boolean isRoot() {
return (this.father == null);
}
public void deleteFather() {
this.father = null;
}
}

Your structure is similar to ona which i have in my application. I solve this problem by creating generic walker, which walks down the three from the root, and using visitor pattern to provide me result of walk.
If you convert it into your problem it will looks like that:
public class SimpleWalker<T>{
private Visitor<T> visitor;
public SimpleWalker(Visitor<T> visitor) {
this.visitor= visitor;
}
public void walk(Member node) {
if (visitor.visit(node)) {
for (Member child : node.children) {
walk(child);
}
}
visitor.leave(node);
}
public T getResult() {
return visitor.getResult();
}
}
then visitor interface
public interface Visitor<T> {
boolean visit(Member node);
void leave(Member node);
T getResult();
}
and implementation will looks like that
public class Pathfinder implements Visitor<List<Member>> {
final private String firstname, secondname;//passed by constructor
boolean found = false;
List<Member> path = new ArrayList<>();
public boolean visit(Member node) {
if (node.firstname.equals(firstname)
&& node.secondname.equals(secondname)) {
found = true;
return false;
}
return true;
}
public void leave(Member node) {
if (found){
path.add(0, node);
}
}
public List<Member> getResult() {
return path;
}
}
advantage of this solution is, whatever you want to do something in tree, such us find element, count number of descendants of somebody, you can use walker, all what you need to do is create new visitor.

This Github project might help if you want to create a Family Tree using Java swing:
https://github.com/r-deleon/familyTree
It uses yFiles for Java library..

Related

How to store only multiple passengers inside the cabin class?

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

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

How can I find and delete a certain node from a linked list. java using these specific classes

I'm trying to do a project and I'm not sure how to find and delete a certain node in a linked list. my professor wants us to use these exact classes.
public class StudentList {
private StudentNode shead ;
public StudentList(){}
public void setShead(StudentNode sh)
{
shead = sh;
}
public StudentNode getShead()
{
return shead;
}
public void deleteStudentNode(StudentNode s)
{
}
public StudentNode findStudentByName(String s)
{
}
}
I won't waste space for the Accessor and Mutator methods for the next classes
student class
public class Student extends Person{
private String major;
private double gpa;
public Student(){}
}
person class
public class Person {
private String name;
private String gender;
public Person(){}
public Person (String n, String g)
{
n = name;
g = gender;
}
}
EDIT -here is the student node
public class StudentNode {
private Student student;
private StudentNode sptr;
private FriendList fptr;
StudentNode()
{ }
public StudentNode(Student s)
{
s = student;
}
public void setStudent(Student s)
{
student = s;
}
public Student getStudent()
{
return(student);
}
public void setSptr(StudentNode s)
{
sptr = s;
}
public StudentNode getSptr()
{
return(sptr);
}
If you want to find or delete a student node with student name, you need to access the name field. You can add some getter/setter for Person class:
public class Person {
private String name;
private String gender;
public Person() {
}
public Person(String n, String g) {
n = name;
g = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then implement the find and delete like this:
public class StudentList {
private StudentNode shead;
public StudentList() {
}
public void setShead(StudentNode sh) {
shead = sh;
}
public StudentNode getShead() {
return shead;
}
private boolean isSameStudent(Student a, Student b) {
return a != null && b != null && a.getName().equals(b.getName());
}
public void deleteStudentNode(StudentNode s) {
if (s == null) {
// Cannot delete a null node
return;
}
if (isSameStudent(s.getStudent(), shead.getStudent())) {
// If the node to delete is head
shead = shead.getSptr();
return;
}
StudentNode ptr = shead;
while (ptr != null) {
if (ptr.getSptr() == null) {
// There is no node after ptr
return;
}
if (isSameStudent(ptr.getSptr().getStudent(), s.getStudent())) {
// The next node is the node to delete
ptr.setSptr(ptr.getSptr().getSptr());
break;
}
ptr = ptr.getSptr();
}
}
public StudentNode findStudentByName(String s) {
StudentNode ptr = getShead();
while (ptr != null) {
if (ptr.getStudent().getName().equals(s)) {
return ptr;
}
ptr = ptr.getSptr();
}
// not found
return null;
}
}
Hop it could help you!

Class Return type when creating a method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
[UML Diagram][1]
I'm studying for the midterm exam next week and I'm practicing some given examples from my professor; however, I am having some trouble with class return type methods.
I attached UML diagram just in case.
What i'm trying to understand is getPerson method in Job class. I don't think i need a array list in Job class to store all the employee. Because I have an array list already in Company class. Also return type is Employee class that I'm not sure how to get person's info using this class return type.
My problems
public Employee getPerson() {} in Job class
public boolean isVacant() {} in Job class
Also would you mind checking getVacantJobs, getFilledJobs, and getAllJobs methods if those are correctly built?
I used iterator to display all the stored jobs.
---------------------------Employee Class -----------------------------
public class Employee {
private String name;
private int id;
public Employee(int id, String name) {
this.name = name;
this.id =id;
}
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public final int getId() {
return id;
}
public final void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + "]";
}
}
----------------------------Job Class--------------------------------------
public class Job {
private String description;
private int id;
private double maxSalary;
public Job(int id, double maxSalary, String description) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
public Job(int id, double maxSalary, String description, Employee e1) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
#Override
public String toString() {
return "Job [description=" + description + ", id=" + id
+ ", maxSalary=" + maxSalary + "]";
}
public final String getDescription() {
return description;
}
public final void setDescription(String description) {
this.description = description;
}
public final double getMaxSalary() {
return maxSalary;
}
public final void setMaxSalary(double maxSalary) {
this.maxSalary = maxSalary;
}
public final int getId() {
return id;
}
public Employee getPerson() {
retrun
}
public final void setPerson(Employee person) {
this.id = person.getId();
}
}
--------------------------Company Class ---------------------------
import java.util.ArrayList;
import java.util.Iterator;
public class Company {
static ArrayList list = new ArrayList();
Iterator itr = list.iterator();
private String name;
public Company(String name) {
this.name = name;
}
public Company() {
// TODO Auto-generated constructor stub
}
public static void addJob(Job j1) {
list.add(j1);
}
public void removeJob(int id) {
list.remove(id);
}
public ArrayList<Job> getVacantJobs() {
while (itr.hasNext()) {
if ((itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getFilledJobs() {
while (itr.hasNext()) {
if (!(itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getAllJobs() {
while (itr.hasNext()) {
System.out.println(itr.next());
}
return null;
}
}
Add field person to Job class.
public class Job {
// .....
private Employee person;
public Employee getPerson() {
return person;
}
public final void setPerson(Employee person) {
this.person = person;
}
public boolean isVacant() {
return person == null;
}
}
And add jobs field to Company class.
public class Company {
// static ArrayList list = new ArrayList(); // You don't need this
// Iterator itr = list.iterator(); // You don't need this.
// .....
private ArrayList<Job> jobs = new ArrayList<>();
public ArrayList<Job> getVacantJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getFilledJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (!job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getAllJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
result.add(job);
return result;
}
}

Two classes making same instance?? java

so i had this exam in university which was to create book class which would have author, title, content and translator.
main requirement was to create only 1 class and create inner classes within it (author and translator)
and one Main class to test it.
Problem was that when i created author and translator objects and tried to change their names, both of them would change names.
Here's my code:
Book Class:
public class Book {
private Author author;
private Translator translator;
private String title;
private String text;
public interface IPerson {
public void setFirstName(String name);
public String getFirstName();
public void setLastName(String name);
public String getLastName();
}
//Author
public class Author implements IPerson{
private String firstName;
private String lastName;
public Author(String f, String l){
firstName = f;
lastName = l;
author = this;
}
public void setFirstName(String name){
this.firstName = name;
}
public String getFirstName(){
return this.firstName;
}
public void setLastName(String name){
this.lastName = name;
}
public String getLastName(){
return this.lastName;
}
}
public Author getAuthor(){
return this.author;
}
//Translator
public class Translator extends Author{
public Translator(String f, String l) {
super(f, l);
translator = this;
}
}
public Translator getTranslator(){
return this.translator;
}
public String getTranslatorFullName(){
return this.getTranslator().getFirstName() + " " + this.getTranslator().getLastName();
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDisplayTitle(){
return getTitle() + " Author: " + this.getAuthor().getFirstName() + " " + this.getAuthor().getLastName();
}
}
Main Class:
public class Main {
public static void main(String[] args){
Book mybook = new Book();
mybook.setTitle("Fight Club");
mybook.setText("First rule of Fight Club, you do not talk about Fight Club");
Book.Author author = mybook.new Author("John","Doe");
Book.Translator translator = mybook.new Translator("Alan","Rickman");
System.out.println(mybook.getDisplayTitle());
System.out.println(mybook.getAuthor().getLastName());
System.out.println(mybook.getAuthor().getFirstName());
System.out.println(mybook.getTranslatorFullName());
System.out.println(mybook.getTranslator().getFirstName());
}
}
It Had to pass these tests, what was my problem?
Don't tell me to make Translator implement IPerson, it was my teachers request to extend
You can fix it like this:
public Author(String f, String l, boolean authorCheck){
firstName = f;
lastName = l;
if(authorCheck)
{
author = this;
}
}
public Author(String f, String l){
firstName = f;
lastName = l;
author = this;
}
public Translator(String f, String l) {
super(f, l, false);
translator = this;
}
It would make more sense if Translator implements IPerson instead of extending Author.
You're making a super(f,l) call in the constructor of Translator. Translator is changing the Author fields as the superclass of Translator is Author.

Categories

Resources