Practice Exercises Java - Learn to program performing exercises with Java

Practice Exercises Java

Learn to program performing exercises with Java

12 Lessons Java with the Solutions - 228 Exercises Java with the solutions
For Beginners, Intermediates and Advanceds


App Practice Exercises Java

The human knowledge belongs to the world
¡The infomation should be free!



Table + array + files - Practice Exercises Java


Lesson 9:

Object persistence


Exercise 9.1:

Table + array + files


Objetive:

Expand the exercise of January 9th (tables + array), so that it contains two new methods, to dump the data of the array into a binary file and restore the data from the file.


Source Code:


package Tables;
public class Table
{
	protected int width, height;

	public Table(int tableWidth, int tableHeight)
	{
		width = tableWidth;
		height = tableHeight;
	}

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

	public final void Save(String name)
	{
		BinaryWriter outputFile = new BinaryWriter(File.Open(name, FileMode.Create));
		outputFile.Write(height);
		outputFile.Write(width);
		outputFile.Close();
	}

	public final void Load(String name)
	{
		BinaryReader inputFile = new BinaryReader(File.Open(name, FileMode.Open));
		height = inputFile.ReadInt32();
		width = inputFile.ReadInt32();
		inputFile.Close();
	}
}
package Tables;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		Table[] tableList = new Table[10];
		Random random = new Random();

		for (int i = 0; i < tableList.length - 1; i++)
		{
			tableList[i] = new Table(random.nextInt(50, 201), random.nextInt(50, 201));
		}
		tableList[0].Save("1.dat");
		tableList[9] = new Table(0, 0);
		tableList[9].Load("1.dat");

		for (int i = 0; i < tableList.length; i++)
		{
			tableList[i].ShowData();
		}

		new Scanner(System.in).nextLine();
	}
}
Exercisey 9.1




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.