Creating Family tree in java .
Trees are such an important structure in computer science. But what more important tree, than our family tree?❤️
👨👩👧👦 ❤️
Made this simple program in java to implement family tree.
Java File
import java.util.*;
class Person {
String name;
boolean married;
String wife;
int noOfChild;
Person[] childs;
public Person(String name){
this.name = name;
}
public Person(String name,boolean married,String wife,Person[] childs,int noOfChild) {
this.name = name;
this.married = married;
this.wife = wife;
this.childs = childs;
this.noOfChild = noOfChild;
}
public Person(String name , boolean married,String wife) {
this.name = name;
this.married = married;
this.wife = wife;
}
}
class familyTree {
static int population;
static Scanner input = new Scanner(System.in);
static Person createTree() {
// Person root = null;
System.out.print("Enter Name : ");
String name = input.next();
System.out.println("Is Married? y or n");
char m = input.next().charAt(0);
boolean married = (m=='y')?true:false;
if(married) {
System.out.println("Enter Wife/husband Name : ");
String wName = input.next();
System.out.println("How many childrens? ");
int n = input.nextInt();
if(n==0) return new Person(name,married,wName);
Person[] childrens = new Person[n];
for(int i=0;i<n;i++) {
System.out.println("Enter child no "+(i+1)+" Of "+name);
childrens[i] = createTree();
}
return new Person(name,married,wName,childrens,(n));
}
else return new Person(name);
}
void display(Person root,int tabs) {
population += 1;
String t = "";
for(int j=0;j<tabs;j++)t+="\t";
System.out.println(t+"----------------");
System.out.println(t+"Name : "+root.name);
if(root.married) {
population += 1;
System.out.println(t+"Wife/Husband name : "+root.wife);
if(root.noOfChild >0) {
System.out.println(t+"Has "+root.noOfChild+" Childrens");
for(int i=0;i<root.noOfChild;i++){
display(root.childs[i],tabs+2);
}
}
}
}
public static void main(String[] args) {
Person root = createTree();
familyTree t = new familyTree();
t.display(root,1);
System.out.println("Total Members : "+t.population);
}
}
Output :
----------------
Name : Henry
Wife/Husband name : alice
Has 3 Childrens
----------------
----------------
Name : william
----------------
Name : richard
Wife/Husband name : ana
Has 2 Childrens
----------------
----------------
Name : rose
----------------
Name : lily
Wife/Husband name : john
----------------
----------------
Name : randy
----------------