Exercises Java with Examples-
Practice Exercises Java 4,5 5 302940

Nested structs - Practice Exercises Java


Lesson 4:

Structures and Strings


Exercise 4.19:

Nested structs


Objetive:

Create a 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 dat of two persons and display them.


Source 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;
		}
	}
}
Exercisey 4.19

Share Now:


Google Ads





Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.