Array of objects: table Learn programming Java

Lesson:

OOP More On Classes


Exercise:

Array of objects: table


Objetive:

Create a class named "Table". It must have a constructor, indicating the width and height of the board. It will have a method "ShowData" which will write on the screen the width and that height of the table. Create an array containing 10 tables, with random sizes between 50 and 200 cm, and display all the data.


Code:

package ArrayOfObjects;
import java.util.*;

public class Table
{
	private float width, height;

	public Table()
	{
	}
	public Table(float width, float height)
	{
		this.width = width;
		this.height = height;
	}

	public final void setWidth(float value)
	{
		width = value;
	}
	public final float getWidth()
	{
		return width;
	}
	public final void setHeight(float value)
	{
		height = value;
	}
	public final float getHeight()
	{
		return height;
	}

	public final void ShowData()
	{
		System.out.printf("Width: %1$s, Heigth: %2$s" + "\r\n", width, height);
	}
}

public class Main
{
	public static void main(String[] args)
	{
		boolean debug = false;

		Table[] myTables = new Table[10];
		Random rnd = new Random();

		for (int i = 0; i < 10; i++)
		{
			myTables[i] = new Table(rnd.nextInt(50, 201), rnd.nextInt(50, 201));
			myTables[i].ShowData();
		}

		if (debug)
		{
			new Scanner(System.in).nextLine();
		}
	}
}

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