Struct Learn programming Java

Lesson:

Arrays, Structures and Strings


Exercise:

Struct


Objetive:

Create a "struct" to store data of 2D points. The fields for each point will be:

x coordinate (short)
y coordinate (short)
r (red colour, byte)
g (green colour, byte)
b (blue colour, byte)

Write a java program which creates two "points", asks the user for their data, and then displays their content.


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 p1, p2 = new point();

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

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

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

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

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

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

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

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

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

		System.out.print("Enter Blue for second point: ");
		p2.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", p1.x, p1.y, p1.r, p1.g, p1.b);

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