Array of struct Learn programming Java

Lesson:

Arrays, Structures and Strings


Exercise:

Array of struct


Objetive:

Expand the previous exercise (struct point), so that up to 1.000 points can be stored, using an "array of struct". Ask the user for data for the first two points and then display them.


Code:

import java.util.*;
public class Main
{
	private final static class point
	{
		public short x;
		public short y;
		public byte r;
		public byte g;

		public byte b;

		public point clone()
		{
			point varCopy = new point();

			varCopy.x = this.x;
			varCopy.y = this.y;
			varCopy.r = this.r;
			varCopy.g = this.g;
			varCopy.b = this.b;

			return varCopy;
		}
	}

	public static void main()
	{
		point[] p = new point[1000];


		System.out.print("Enter X for first point: ");
		p[0].x = Short.parseShort(new Scanner(System.in).nextLine());

		System.out.print("Enter Y for first point: ");
		p[0].y = Short.parseShort(new Scanner(System.in).nextLine());

		System.out.print("Enter Red for first point: ");
		p[0].r = Byte.parseByte(new Scanner(System.in).nextLine());

		System.out.print("Enter Green for first point: ");
		p[0].g = Byte.parseByte(new Scanner(System.in).nextLine());

		System.out.print("Enter Blue for first point: ");
		p[0].b = Byte.parseByte(new Scanner(System.in).nextLine());


		System.out.print("Enter X for second point: ");
		p[1].x = Short.parseShort(new Scanner(System.in).nextLine());

		System.out.print("Enter Y for second point: ");
		p[1].y = Short.parseShort(new Scanner(System.in).nextLine());

		System.out.print("Enter Red for second point: ");
		p[1].r = Byte.parseByte(new Scanner(System.in).nextLine());

		System.out.print("Enter Green for second point: ");
		p[1].g = Byte.parseByte(new Scanner(System.in).nextLine());

		System.out.print("Enter Blue for second point: ");
		p[1].b = Byte.parseByte(new Scanner(System.in).nextLine());


		System.out.printf("P1 is located in (%1$s,%2$s), colour (%3$s,%4$s,%5$s)" + "\r\n", p[0].x, p[0].y, p[0].r, p[0].g, p[0].b);

		System.out.printf("P2 is located in (%1$s,%2$s), colour (%3$s,%4$s,%5$s)" + "\r\n", p[1].x, p[1].y, p[1].r, p[1].g, p[1].b);
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.