Exercise
Nested structs
Objetive
Write a java Struct to store two data for a person:
name and date of birth.
The date of birth must be another struct consisting on day, month and year.
Finally, create an array of persons, ask the user for the data of two persons and display them.
Example Code
import java.util.*;
public class Main
{
private final static class person
{
public String Name;
public dateBirth Date = new dateBirth();
public person clone()
{
person varCopy = new person();
varCopy.Name = this.Name;
varCopy.Date = this.Date.clone();
return varCopy;
}
}
private final static class dateBirth
{
public int Day;
public int Month;
public int Year;
public dateBirth clone()
{
dateBirth varCopy = new dateBirth();
varCopy.Day = this.Day;
varCopy.Month = this.Month;
varCopy.Year = this.Year;
return varCopy;
}
}
static void main(String[] args)
{
int d = 0, m = 0, y = 0;
int total = 1;
person[] p = new person[total];
for (int i = 0; i <= total; i++)
{
System.out.print("Enter name: ");
String Name = new Scanner(System.in).nextLine();
System.out.println();
p[i].Name = Name;
System.out.print("Enter day: ");
d = Integer.parseInt(new Scanner(System.in).nextLine());
System.out.println();
p[i].Date.Day = d;
System.out.print("Enter month: ");
d = Integer.parseInt(new Scanner(System.in).nextLine());
System.out.println();
p[i].Date.Month = m;
System.out.print("Enter year: ");
d = Integer.parseInt(new Scanner(System.in).nextLine());
System.out.println();
p[i].Date.Year = y;
}
}
}