Cities - persistence Learn programming Java

Lesson:

Object Persistence


Exercise:

Cities - persistence 33


Objetive:

Create a new version of the "cities database" (which you improved on March 13th), using persistence to store its data instead of text files.


Code:

package PersistenceCities;
public class City implements Serializable
{

	private String name;
	private int inhabitants;

	//CONSTRUCTORS
	public City()
	{

	}

	public City(String name, int inhabitants)
	{
		this.name = name;
		this.inhabitants = inhabitants;
	}

	//GETTERS && SETTERS
	public final String getName()
	{
		return name;
	}
	public final void setName(String value)
	{
		name = value;
	}

	public final int getInhabitants()
	{
		return inhabitants;
	}

	public final void setInhabitants(int value)
	{
		inhabitants = value;
	}

}

package PersistenceCities;
public class Serializador
{
    private String nombre;

	public Serializador(String nombreFich)
	{
		nombre = nombreFich;
	}

	public final void Guardar(City objeto)
	{
		IFormatter formatter = new BinaryFormatter();
		Stream stream = new java.io.FileOutputStream(nombre);
		formatter.Serialize(stream, objeto);
		stream.Close();
	}

	public final City[] Cargar()
	{
		City objeto;
		IFormatter formatter = new BinaryFormatter();
		Stream stream = new java.io.FileInputStream(nombre);
		objeto = (City)formatter.Deserialize(stream);
		stream.Close();
		return objeto;
	}
}

package PersistenceCities;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		ArrayList cities = new ArrayList();

		int currentCityNumber;
		String option;
		String textToSearch;
		boolean found;
		String textToModify;
		boolean finished = false;
		//  City currentCity;
		String line;
		// City newCity;

		City[] city = new City[2000];
		int count = 0;

		if ((new java.io.File("data.dat")).isFile())
		{

			Serializador s = new Serializador("data.dat");
			city = (City[])s.Cargar();
		}

		do
		{
			System.out.println();
			System.out.println("Cities database");
			System.out.println();
			System.out.println("1.- Add a new city");
			System.out.println("2.- View all cities");
			System.out.println("3.- Modify a record");
			System.out.println("4.- Insert a new record");
			System.out.println("5.- Delete a record");
			System.out.println("6.- Search in the records");
			System.out.println("7.- Correct the capitalization of the names");
			System.out.println("0.- Exit");
			System.out.println();
			System.out.print("Choose an option: ");
			option = new Scanner(System.in).nextLine();

			switch (option)
			{
				//0.-Exit
				case "0":
					finished = true;
					break;


				//1 .- Add a new city (at the end of the existing data)
				case "1":
					System.out.printf("Entering data for city number %1$s" + "\r\n", cities.size() + 1);
					System.out.print("Enter the city name: ");
					City newcity = new City();
					newcity.Name = new Scanner(System.in).nextLine();
					System.out.print("Enter the inhabitants numbers: ");
					newcity.Inhabitants = Integer.parseInt(new Scanner(System.in).nextLine());
					cities.add(newcity);
					System.out.println("The data was entered correctly");
					break;


				//2 .- View all cities (name and inhabitants)
				case "2":
					for (int i = 0; i < cities.size(); i++)
					{
						currentCity = (city)cities.get(i);
						System.out.printf("%1$s: %2$s, %3$s inhabitants" + "\r\n", i + 1, currentCity.name, currentCity.inhabitants);
					}
					System.out.println();
					break;


				//3 .- Modify a record (rename and / or change number of inhabitants)
				case "3":
					System.out.print("Enter the city number: ");
					currentCityNumber = Integer.parseInt(new Scanner(System.in).nextLine());
					currentCity = (city)cities.get(currentCityNumber - 1);
					System.out.printf("Enter a new data for a city number: %1$s" + "\r\n", currentCityNumber);
					System.out.printf("City name (was %1$s; hit ENTER to leave as is): ", currentCity.name);
					textToModify = new Scanner(System.in).nextLine();
					if (!textToModify.equals(""))
					{
						currentCity.name = textToModify;
					}
					System.out.printf("Inhabitants (was %1$s; hit ENTER to leave as is): ", currentCity.inhabitants);
					textToModify = new Scanner(System.in).nextLine();
					if (!textToModify.equals(""))
					{
						currentCity.inhabitants = Integer.parseInt(textToModify);
					}
					cities.set(currentCityNumber - 1, currentCity);
					System.out.println();
					break;


				//4 .- Insert a new record (in a specified position,
				//moving the following ones to the right).
				case "4":
					System.out.print("Enter the number of the city to modify: ");
					currentCityNumber = Integer.parseInt(new Scanner(System.in).nextLine());
					currentCity = (city)cities.get(currentCityNumber - 1);
					System.out.printf("Insert a new data at %1$s position: " + "\r\n", currentCityNumber);
					System.out.print("City name: ");
					currentCity.name = new Scanner(System.in).nextLine();
					System.out.print("Inhabitants: ");
					currentCity.inhabitants = Integer.parseInt(new Scanner(System.in).nextLine());
					cities.add(currentCityNumber - 1, currentCity);
					break;


				//5 .- Delete a record (moving the following 
				//  ones to the left so that no empty spaces are left)
				case "5":
					System.out.print("Enter the city number for delete: ");
					currentCityNumber = Integer.parseInt(new Scanner(System.in).nextLine());

					System.out.printf("Deleting the number %1$s" + "\r\n", currentCityNumber);
					cities.remove(currentCityNumber - 1);
					break;


				//6 .- Search in the records (display the ones which contain 
				//a certain text in their name, whether in upper or lower case, 
				//using partial search)
				case "6":
					System.out.print("Enter the text to search: ");
					textToSearch = new Scanner(System.in).nextLine();
					found = false;
					for (int i = 0; i < cities.size(); i++)
					{
						currentCity = (city)cities.get(i);
						if (currentCity.name.toUpperCase().indexOf(textToSearch.toUpperCase()) >= 0)
						{
							System.out.printf("%1$s found in %2$s" + "\r\n", textToSearch, currentCity.name);
							found = true;
						}
					}
					if (!found)
					{
						System.out.println("Not found.");
					}
					break;


				// 7 .- Correct the capitalization of the names
				//(turn into uppercase the first letter and the ones after 
				//a space, and make the rest lowercase).
				case "7":
					for (int i = 0; i < cities.size(); i++)
					{
						currentCity = (city)cities.get(i);
						// First, the whole name to lower case
						String lowerCaseName = currentCity.name.toLowerCase();
						// then, first letter to uppercase
						String correctedName = lowerCaseName.substring(0, 1).toUpperCase() + lowerCaseName.substring(1);
						// and then the letters after a space
						for (int j = 1; j < correctedName.length() - 2; j++)
						{
							if (correctedName.charAt(j) == ' ')
							{
								correctedName = correctedName.substring(0, j) + " " + correctedName.substring(j + 1, j + 1 + 1).toUpperCase() + correctedName.substring(j + 2);
							}
						}

						currentCity.name = correctedName;
					}
					break;


				default:
					System.out.println("Wrong option ");
					break;

			}

		} while (!finished);

		outputFile = File.CreateText("data.dat");

		for (int i = 0; i < cities.size(); i++)
		{
			currentCity = (city)cities.get(i);
			outputFile.WriteLine(currentCity.name);
			outputFile.WriteLine(currentCity.inhabitants);
		}

		outputFile.Close();

	}
}