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

Table + coffetable + array - Practice Exercises Java


Lesson 7:

More on classes


Exercise 7.3:

Table + coffetable + array


Objetive:

Create a project named "Tables2", based on the "Tables" project.

In it, create a class "CoffeeTable" that inherits from "Table". Its method “ShowData", besides writing the width and height, must display "(Coffee table)."

Create an array that contains 5 tables and 5 coffee tables. The tables must have random sizes between 50 and 200 cm, and the coffee tables from 40 to 120 cm. Show all their data.


Source Code:


package Tables2;
import java.util.*;

public class CoffeeTable extends Table
{
	public CoffeeTable(float width, float height)
	{
		this.width = width;
		this.height = height;
	}
	@Override
	public void ShowData()
	{
		System.out.printf("(Coffee table) Width: %1$s, Heigth: %2$s" + "\r\n", width, height);
	}
}

public class Table
{
	protected 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 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 = 1; i <= 10; i++)
		{
			if ((i % 2 == 0) && (i != 1))
			{
				myTables[i - 1] = new Table(rnd.nextInt(50, 201), rnd.nextInt(50, 201));
				myTables[i - 1].ShowData();
			}
			else
			{
				myTables[i - 1] = new CoffeeTable(rnd.nextInt(40, 121), rnd.nextInt(40, 121));
				myTables[i - 1].ShowData();
			}

		}

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

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.