Laboratory‎ > ‎

Java

The following is a list of Java programming assignments done by Seunghoon Kim for UIUC-CS125 Introduction to Computer Science in Spring 2003. To be used for personal references only.




CS125 MP1: Spacing

A program for performing various calculations involving the floor space in a building. This version of the solution makes use of casting.

Spacing.java

// Class: Spacing
// Seunghoon Kim
// 2/13/2003
 
// CS 125 MP 1
// Building Space Calculations 
 
public  class Spacing
{
    // Method: main
    //    - controls main execution of program
    public static void main(String[] args)
    {    
	int buildingsize;
	int groundfloor;
	int rooms;
	int otherfloor;
	double avgarea;
	double percent;
 
	// prints out the name of the program
	System.out.println("Building Area Calculation Program");
	System.out.println("+++++++++++++++++++++++++++++++++");
	// asks for the size of the building
	System.out.print("Enter the number of square feet in the building: ");
	// stores the input as    a variable buildingsize
 	buildingsize = Keyboard.readInt();
	// asks for the size of the ground floor
	System.out.print("Enter the number of square feet on ground floor: ");
	// stores the input as    a variable groudfloor
	groundfloor = Keyboard.readInt();
	// asks for the number of rooms in the building
	System.out.print("How many rooms does the building have?: ");
	// stores the input as a variable rooms
	rooms = Keyboard.readInt();
 
	// calculation of average area per room
	avgarea = (double) buildingsize/rooms;
	// size of the floors other than the ground floor
	otherfloor = buildingsize - groundfloor;
	// calculation of percentage of the area other floors are occupying in the building
	percent = (double) otherfloor/buildingsize*100;
 
	// prints out a blank line
	System.out.println();
	// prints out the average area per room
	System.out.println("There is an average of " + avgarea + " square feet per room.");
	// prints out the area of the floors other than the ground floor
	System.out.println(otherfloor + " of the " + buildingsize + " square feet of the building are on floors other than the
            ground floor.");
	// prints out the percentage of area of other floors in the building
	System.out.println("This is " + percent + "% of the total area.");
 
	// end of the program
    }
}

Spacing.class

/* default package */
 
public class Spacing extends java.lang.Object
{
    /* Constructors */
    public Spacing() {
    }
 
 
    /* Methods */
    public static void main(java.lang.String[]) {
    }
 
}


CS125 MP2: Property Taxes

This program calculates the property tax that is owed on a piece of property. Depending on whether it has a building on the property, the size of the building, and floors the building has will affect the amount of the property tax.

PropertyTax.java

public class PropertyTax
{
   public static void main(String[]args)
   {
 
      int propsize;
      char building;
      int bldgsize = 0;
      int bldgflr = 0;
      char taxpay;
      char correct;
      int taxclass;
      int proptax = 0;
 
      System.out.println("Property Tax Calculation Program");
      System.out.println("++++++++++++++++++++++++++++++++");
      System.out.println();
 
      do
      {
         System.out.print("Enter size of the property: ");
         propsize = Keyboard.readInt();
         System.out.print("Is there a building? (Y/N): ");
         building = Keyboard.readChar();
 
         if (building == 'Y')
         {
            System.out.print("Enter size of building: ");
            bldgsize = Keyboard.readInt();
            System.out.print("Enter number of floors: ");
            bldgflr = Keyboard.readInt();
         }
 
         System.out.print("Annual or quarterly bill? (A/Q): ");
         taxpay = Keyboard.readChar();
         System.out.print("Is the above information correct? (Y/N): ");
         correct = Keyboard.readChar();
 
      } while (correct == 'N');
 
// For the categories of tax classes, numbers are used instead of alphabets,
// in order to make the process a bit simpler.
      if (propsize < 10000)
         taxclass = 1;
      else if (propsize < 18000)
         taxclass = 2;
      else
         taxclass = 3;
 
      if (bldgsize > 7500)
         taxclass = taxclass + 2;
      else if (bldgsize >= 3000)
         taxclass++;
 
      if (taxclass == 1)
         proptax = 1000;
      if (taxclass == 2)
         proptax = 1500;
      if (taxclass == 3)
         proptax = 2500;
      if (taxclass == 4)
         proptax = 4000;
      if (taxclass == 5)
         proptax = 5000;
 
      if (bldgflr == 2)
         proptax = proptax + 500;
      if (bldgflr == 3)
         proptax = proptax + 600;
      if (bldgflr > 3)
         proptax = proptax + 730;
 
      if (taxpay == 'Q')
         System.out.println("The quarterly tax bill is: $" + (proptax/4) + ".");
      else
         System.out.println("The annual tax bill is: $" + proptax + ".");
 
   }
}

PropertyTax.class

/* default package */
 
public class PropertyTax extends java.lang.Object
{
    /* Constructors */
    public PropertyTax() {
    }
 
 
    /* Methods */
    public static void main(java.lang.String[]) {
    }
 
}

CS125 MP3: Building Construction

A program for adding buildings to an existing map of the area, and keeping a record of the order in which the buildings are added to the area.

Construction.java

public class Construction
{
	public static void main(String[] args)
	{
		char[][] area = new char[7][9];
		char inputbldg;
		char bldgtype;
		int row;
		int column;
		int[][] record = new int[62][2];
		int count = 0;
 
		System.out.println("Map Generator for Beachfront Property");
		System.out.println("+++++++++++++++++++++++++++++++++++++");
		System.out.println();
 
		System.out.print("Do you have a building to input? (Y/N): ");
		inputbldg = Keyboard.readChar();
 
		while (inputbldg == 'Y')
		{
			System.out.print("[H]otel or [P]rivate residence?: ");
			bldgtype = Keyboard.readChar();
 
			if (bldgtype == 'P')
			{	
				System.out.print("   Row of house: ");
				row = Keyboard.readInt();
				System.out.print("   Column of house: ");
				column = Keyboard.readInt();
 
				if ((area[row][column] == 'H') || (area[row][column] == 'P'))
				System.out.println("That land is taken; you get a tent instead.");
				else
				{
					area[row][column] = 'P';
					System.out.println("House permit is granted.");
 
					record[count][0] = row;
					record[count][1] = column;
					count = (count+1);
				}
 
			}
 
			if (bldgtype == 'H')
			{
				System.out.print("   Row of hotel: ");
				row = Keyboard.readInt();
				System.out.print("   Left column of hotel: ");
				column = Keyboard.readInt();
 
				if ((area[row][column] == 'P') || (area[row][column] == 'H') || (area[row][(column+1)] == 'P') ||
                                    (area[row][(column+1)] == 'H'))
					System.out.println("At least one of those spots is occupied!");
				else 
				{
					area[row][column] = 'H';
					area[row][(column+1)] = 'H';
					System.out.println("Hotel construction is approved.");
 
					record[count][0] = row;
					record[count][1] = column;
					count = (count+1);
				}
 
			}
			System.out.println();
			System.out.print("Do you have a building to input? (Y/N): ");
			inputbldg = Keyboard.readChar();
		}
 
		//Construction history
		int limit = (count-1);
		System.out.println("Here is the construction history: ");
		System.out.println();
 
		for(count=0; count<=limit; count++)
		{
			row = record[count][0];
			column = record[count][1];
 
			if (area[row][column] == 'P')
				System.out.println("Residence at (" + row + ", " + column + ") : Private");
			if (area[row][column] == 'H')
				System.out.println("Residence at (" + row + ", " + column + ") : Hotel");
		}
		System.out.println();
 
		//Building map
		System.out.println("Here is the building map:");
		System.out.println();
		System.out.println("XXXXXXXXXXXXXXXXXXXXX");
		for(row=0; row<=6; row++)
		{
			System.out.print("X ");
			for(column=0; column<=8; column++)
			{
				if (area[row][column] == 'P')
					System.out.print("P ");
				else if (area[row][column] == 'H')
					System.out.print("H ");
				else
					System.out.print("  ");
			}
			System.out.println("X");
		}
		System.out.println("XXXXXXXXXXXXXXXXXXXXX");
 
	}
}

Construction.class

/* default package */
 
public class Construction extends java.lang.Object
{
    /* Constructors */
    public Construction() {
    }
 
 
    /* Methods */
    public static void main(java.lang.String[]) {
    }
 
}

CS125 MP4: Land Purchase Control

PurchaseControl.java

A class whose methods assist with various phases of the land-purchase process

public class PurchaseControl
{
 
   // processSelection
   //	- parameters : menuChoice - integer variable selected by the user in menuSelection
   //		       map - 2-D array of PlotOfLand info
   //	- return value : 2-D array of PlotOfLand info(map)
   //	- takes in integer value menuChoice(1-3), and depending on that value, 
   //		it makes different method calls
   public static PlotOfLand[][] processSelection(int menuChoice, PlotOfLand[][] map)
   {
   	if (menuChoice == 1)
	   map = MapManipulation.createMap();
   	else if (menuChoice == 2)
   	   purchasePlotOfLand(map);
   	else 
   	   MapManipulation.printMap(map);
 
   	return map; 
   }
 
 
   // obtainCoordinates
   //	- parameters : map - 2-D array of PlotOfLand info
   //		       size - char value indicating whether the plot size is small or large
   //	- return value : reference to a CoordPair object
   //	- asks the user for coordinates of plot, and calls method checkCoords in MapManipulation
   //		to test if that space is available, and returns the coordinates of approved plot location
   //		otherwise, it returns (-1,-1) which is the error code
   public static CoordPair obtainCoordinates(PlotOfLand[][] map, char size)
   {
	CoordPair mappoint;
	mappoint = new CoordPair();
	char again = 'Y';
	boolean endloop = false;
 
   	if (size == 'S')
   	{
   		do{
   			System.out.println("Enter coordinates of plot: ");
   			System.out.print("   row: ");
   			mappoint.xValue = Keyboard.readInt();
   			System.out.print("   column: ");
   			mappoint.yValue = Keyboard.readInt();
 
   			endloop = MapManipulation.checkCoords(map,mappoint);
 
   			if (endloop == false)
   			{
   				System.out.println("You cannot place your plot there. ");
   				System.out.println("Choose new coordinates? (Y/N): ");
   				again = Keyboard.readChar();
   			}
   		}while((again == 'Y')&&(endloop == false));	
   	}
 
   	else if (size == 'L')
   	{
   		do{
 			int temprow = 0;
 			int tempcolumn = 0; 			
 
   			System.out.println("Enter lower left coordinates of plot: ");
   			System.out.print("   row: ");
   			temprow = Keyboard.readInt();
   			System.out.print("   column: ");
   			tempcolumn = Keyboard.readInt();
 
   			for (int i=0; i < 2; i++)
   			{
   				mappoint.xValue = temprow + i;
   				for (int j=0; j < 2; j++)
   				{
  					mappoint.yValue = tempcolumn + j;
  					endloop = MapManipulation.checkCoords(map,mappoint);
   			   		if (endloop == false)
   					{
   						j = 2;
   						i = 2;
   					}
   				}
   			}
 
   			if (endloop == false)
   			{
   				System.out.println("You cannot place your plot there. ");
   				System.out.print("Choose new coordinates? (Y/N): ");
   				again = Keyboard.readChar();
   			}
   			else
   			{
   				mappoint.xValue = mappoint.xValue-1;
   				mappoint.yValue = mappoint.yValue-1;
   			}
 
   		}while((again == 'Y')&&(endloop == false));   		
    	}   		
 
  	if (again == 'N')
  	{
   		mappoint.xValue = -1;
   		mappoint.yValue = -1;
   	}
 
   	return mappoint;
}
 
 
// purchasePlotOfLand
//	- parameters : map - 2-D array of PlotOfLand info
//	- return value : none
//	- declares and initializes an PlotOfLand variable pt, receives coordinate values from the method 
//		obtainCoordinates and sets them into pt.lowerLeft, once all the instance variables are set,
//		calls made to the method writeLotToMap in the class MapManipulation
public static void purchasePlotOfLand(PlotOfLand[][] map)
{
	PlotOfLand pt;
	pt = new PlotOfLand();
	pt.lowerLeft = new CoordPair();
	char tempSize;
 
	System.out.print("Do you wish a small or large plot? (S/L): ");
	tempSize = Keyboard.readChar();
 
	while ((tempSize != 'S')&&(tempSize != 'L'))
	{
		System.out.println("That is not a legal choice!");
		System.out.print("Enter a new selection: "); 
		tempSize = Keyboard.readChar();
	}
 
 
	pt.lowerLeft = obtainCoordinates(map, tempSize);
 
	if (tempSize == 'S')
		pt.sizeType = new String("small");
	if (tempSize == 'L')
		pt.sizeType = new String("large");
 
	if ((pt.lowerLeft.yValue >= 0)&&(pt.lowerLeft.xValue >= 0))
	{
		System.out.print("Enter customer ID: ");
		pt.customerID = Keyboard.readInt();
		MapManipulation.writeLotToMap(map, pt);
	}
}
 
 
 
   // menuSelection
   //    - return value : integer holding legal menu selection
   //    - obtains a legal choice from menu and returns it
   public static int menuSelection()
   {
      System.out.println("Select an option from menu: ");
      System.out.println("   [1] Initialize Map");
      System.out.println("   [2] Purchase Land Plot");
      System.out.println("   [3] Print Map");
      System.out.println("   [4] Quit");
      System.out.print("Enter selection: ");
      int selection = Keyboard.readInt();
      while ((selection < 1) || (selection > 4))
      {
         System.out.println("That is not a legal choice!");
         System.out.print("Enter a new selection: ");
         selection = Keyboard.readInt();
      }
      return selection;
   }
}


PurchaseControl.class

/* default package */
 
public class PurchaseControl extends java.lang.Object
{
    /* Constructors */
    public PurchaseControl() {
    }
 
 
    /* Methods */
    public static PlotOfLand[][] processSelection(int, PlotOfLand[][]) {
    }
 
    public static CoordPair obtainCoordinates(PlotOfLand[][], char) {
    }
 
    public static void purchasePlotOfLand(PlotOfLand[][]) {
    }
 
    public static int menuSelection() {
    }
 
}

MapManipulation.java

A class whose methods manipulate a two-dimensional array representing a building layout map.

public class MapManipulation
{
	// class variable unsold
	public static PlotOfLand unsold;
 
 
	// createMap
	//	- parameters : none
	//	- return value : a 2-D array of PlotOfLand references(map)
	//	- asks for the row and column numbers, and creates a 2-D array of type PlotOfLand and returns
	public static PlotOfLand[][] createMap()
	{
		int rows = 0;
		int columns = 0;
 
		while((rows < 1)||(columns < 1))
		{
			System.out.print("Enter number of rows: ");
			rows = Keyboard.readInt();
			System.out.print("Enter number of columns: ");
			columns = Keyboard.readInt();
			if((rows < 1)||(columns < 1))
				System.out.println("You must enter positive numbers!");
		}
 
		PlotOfLand[][] map;
		map = new PlotOfLand[rows][columns];
 
		for(int i=0; i < rows; i++)
		{
			for(int j=0; j < columns; j++)
			{
				map[i][j] = new PlotOfLand();
				map[i][j] = unsold;
			}
		}		
 
		return map;
	}
 
 
	// writeLotToMap
	//	- parameters : map - 2-D array of PlotOfLand info
	//		       pt - a reference to one PlotOfLand object
	//	- return value : none
	// 	- takes in the PlotOfLand variable pt that holds all the information about specific
	//		location in the map array, and puts in the values held in instance variable pt
	//		into the specific location in the map array 
	public static void writeLotToMap(PlotOfLand[][] map, PlotOfLand pt)
	{
		if (pt.sizeType.equals("small"))
			map[pt.lowerLeft.xValue][pt.lowerLeft.yValue] = pt;
		else if (pt.sizeType.equals("large"))
		{
			map[pt.lowerLeft.xValue][pt.lowerLeft.yValue] = pt;
			map[pt.lowerLeft.xValue][(pt.lowerLeft.yValue+1)] = pt;
			map[(pt.lowerLeft.xValue+1)][pt.lowerLeft.yValue] = pt;
			map[(pt.lowerLeft.xValue+1)][(pt.lowerLeft.yValue+1)] = pt;
		}
	}
 
 
   // checkCoords
   //    - parameters : map - two-dimensional array of PlotOfLand info
   //                 : mapPoint - two-dimensional coordinate in map
   //    - return value : a boolean indicating whether or not the
   //                       coordinate is available for sale in the map
   //    - if the parameter coordinate is both an actual map coordinate, and
   //         is the coordinate of an unsold plot in the map, return true.
   //         Otherwise (i.e. if the coordinate is either off the map or is
   //         in use by a purchased plot) then return false.
   public static boolean checkCoords(PlotOfLand[][] map, CoordPair mapPoint)
   {
      boolean status;
      if ((mapPoint.xValue < 0) || (mapPoint.xValue >= map.length) ||
               (mapPoint.yValue < 0) || (mapPoint.yValue >= map[0].length))
         status = false;
      else if (map[mapPoint.xValue][mapPoint.yValue] != unsold)
         status = false;
      else
         status = true;
 
      return status;
   }
 
 
   // printMap
   //    - prints out map information in a formatted fashion 
   public static void printMap(PlotOfLand[][] map)
   {
      for (int i = 0; i < 4 * map[0].length + 3; i++) 
         System.out.print('X');
      System.out.println();
 
      for (int i = 0; i < map.length; i++)
      {
         System.out.print("X ");
         for (int j = 0; j < map[0].length; j++)
         {
            if (map[i][j].sizeType.equals("unsold"))
               System.out.print("--- ");
            else if (map[i][j].sizeType.equals("large"))
               System.out.print(map[i][j].customerID + " ");
            else 
               System.out.print(map[i][j].customerID + " ");
         } 
         System.out.println('X');
      }
 
      for (int i = 0; i < 4 * map[0].length + 3; i++) 
         System.out.print('X');
      System.out.println();
   }
}

MapManipulation.class

/* default package */
 
public class MapManipulation extends java.lang.Object
{
    /* Fields */
    public static PlotOfLand unsold;
 
    /* Constructors */
    public MapManipulation() {
    }
 
 
    /* Methods */
    public static PlotOfLand[][] createMap() {
    }
 
    public static void writeLotToMap(PlotOfLand[][], PlotOfLand) {
    }
 
    public static boolean checkCoords(PlotOfLand[][], CoordPair) {
    }
 
    public static void printMap(PlotOfLand[][]) {
    }
 
}

CS125 MP5: Building Residence Information System

Building.java

A class implementing a collection of rooms of various kinds

public class Building
{
 
	protected static Room[] RoomArr;
	protected static int rooms;
 
	// Building
   	//    - constructor
   	//    - initializes object to default Building
	public Building()
	{
		RoomArr = new SingleResident[2];
		rooms = 0;
	}
 
   // Building
   //    - constructor
   //    - parameter : OldCollection - Building class variable
   //    - copies Building class variable OldCollection to
   //          a new Building class variable
   	public Building(Building OldCollection)
	{
		rooms = OldCollection.rooms;
		RoomArr = new SingleResident[(OldCollection.RoomArr.length * 2)];
		for(int i=0; i<=(OldCollection.RoomArr.length); i++)
			RoomArr[i] = OldCollection.RoomArr[i];
	}
 
   // appendRoom
   //	 - parameter : paramRoom - Room class variable
   //    - no return value
   //    - copies paramRoom into a room array RoomArr
	public static void appendRoom(Room paramRoom)
	{
		RoomArr[rooms] = paramRoom.copy();
		rooms++;
	}
 
   // printAll
   //    - prints out info to screen
	public static void printAll()
	{
		for(int i=0; i<rooms; i++)
		   RoomArr[i].print();
		System.out.println();
	}
 
}

Room.java

A class representing a room, numbered as if in some building of some kind

public class Room
{
   // Room
   //    - constructor
   //    - initializes object to default room
   public Room()
   {
      roomNumber = 0;
      roomSize = 0;
   }
 
 
   // Room
   //    - constructor
   //    - parameters : paramRoomNumber - the number of this room
   //                 : paramRoomSize - the size of this room
   //    - initializes office to have the parameter room number and
   //          size; assumption about parameters is that both are
   //          non-negative
   public Room(int paramRoomNumber, int paramRoomSize)
   {
      roomNumber = paramRoomNumber;
      roomSize = paramRoomSize;
   }
 
 
   // getRoomNumber
   //    - return value : an integer storing a room number
   //    - returns the room number of this room
   public int getRoomNumber()
   {
      return roomNumber;
   }
 
 
   // getRoomSize
   //    - return value : an integer storing the room size
   //    - returns the room size of this room
   public int getRoomSize()
   {
      return roomSize;
   }
 
 
   // print
   //    - prints out info to screen
   public void print()
   {
      System.out.println("Room number: " + roomNumber);   
      System.out.println("Size of room: " + roomSize);
   }
 
 
   // copy
   //    - return type: a reference to another Room object
   //    - creates and returns a copy of this object
   public Room copy()
   {
      return new Room(roomNumber, roomSize);
   } 
 
 
   private int roomNumber;   // room number of room
   private int roomSize;     // size of room
}

SingleResident.java

A subclass of room that inherits everything in room class and adds resident's name

public class SingleResident extends Room
{
 
   private String ResidentName;
 
   // Room
   //    - constructor
   //    - initializes object to default room
   public SingleResident()
   {
      super();
      ResidentName = "";
   }
 
 
   // Room
   //    - constructor
   //    - parameters : paramRoomNumber - the number of this room
   //                 : paramRoomSize - the size of this room
   //    - initializes office to have the parameter room number and
   //          size; assumption about parameters is that both are
   //          non-negative
   public SingleResident(int paramRoomNumber, int paramRoomSize, String paramResidentName)
   {
      super(paramRoomNumber, paramRoomSize);
      ResidentName = paramResidentName;
   }
 
   // getResidentName
   //    - return value : a string storing the resident's name
   //    - returns the resident's name occupying this room
   public String getResidentName()
   {
   	return ResidentName;
   }
 
 
   // print
   //    - prints out info to screen
   public void print()
   {
      super.print();
      System.out.println("Resident's name: " + ResidentName);
   }
 
 
   // copy
   //    - return type: a reference to another Room object
   //    - creates and returns a copy of this object
   public Room copy()
   {
      int tempRoomNumber = super.getRoomNumber();
      int tempRoomSize = super.getRoomSize();
      return new SingleResident(tempRoomNumber, tempRoomSize, ResidentName);
   } 
 
}

CS125 MP6: Real Estate Development and Controller

Controller.java

An object of this class serves as the controller for our building-purchase program, dealing with user interaction and starting subparts of the program until the user finally decides to quit.

import java.io.*;
 
public class Controller
{
   // Controller
   //    - constructor
   //    - initializes object to default values -- no customers,
   //        buildings, or developments, and default administrator
   //        access, which is "not an administrator"
   public Controller()
   {
      isAdministrator = false;
      developments = new String[0];
      clients = new int[0];
      edifices = new Building[0];
   }
 
 
   // operate
   //    - this method is the main program loop, in that once 
   //       this method is called, it does not return until the 
   //       user decides to quit. This method is responsible for
   //       acquiring user input from the menu and activating the
   //       appropriate actions based on user input. In addition,
   //       whether or not the user is an administrator is 
   //       determined at the start of this method, so that the
   //       other methods will all know what choices are available
   //       to this user.  
   public void operate()
   {
      System.out.println("Welcome to the Building Purchasing Controller.");
      System.out.print("Are you an administrator? (Y/N): ");
      char adminChoice = Keyboard.readChar();
      if (adminChoice == 'Y')
         isAdministrator = true;
      else
         isAdministrator = false; 
      System.out.println();
 
      char menuChoice;
      boolean quittingNotWanted = true;
      do 
      {
         menuChoice = getMainMenuChoice();
 
         if (menuChoice == 'P')
            purchaseBuilding(); 
         else if (menuChoice == 'V')
            viewCustomerHistory();
         else if (menuChoice == 'A')
            administration();
         else if (menuChoice == 'Q')
            quittingNotWanted = false;
 
      } while (quittingNotWanted);
 
      System.out.println("That is all!");
   }
 
 
 
   // getMainMenuChoice
   //    - return value : a character that is a legal menu choice
   //                       for the status of the user
   //    - prints out menu of user selections, with the menu being
   //       appropriate to whether the user is an administrator 
   //       or not. Then, prompts for a menu selection. The method
   //       will reprompt repeatedly as long as the user's selection
   //       is illegal; once a legal selection is made, that selection
   //       is returned.   
   private char getMainMenuChoice()
   {
      System.out.println("Please select one of the following options:");
      System.out.println("   [P] Purchase a Building");
      System.out.println("   [V] View Customer History");
      if (isAdministrator)
         System.out.println("   [A] Administration Options");
      System.out.println("   [Q] Quit Controller");
 
      char menuChoice; 
      boolean menuChoiceIllegal = true;
      do
      {
         System.out.print("Enter choice: ");
         menuChoice = Keyboard.readChar();
         if (     (menuChoice == 'P') || 
                  (menuChoice == 'V') || 
                  (isAdministrator && (menuChoice == 'A')) || 
                  (menuChoice == 'Q'))
            menuChoiceIllegal = false;
         else
            System.out.println("That is not a legal menu choice!");
         System.out.println();
      } while (menuChoiceIllegal);
 
      return menuChoice;
   }
 
 
 
   // ********************** Purchasing methods *********************
 
   private void purchaseBuilding() 
   {
	System.out.print("Enter customer ID: ");
	int custID = Keyboard.readInt();
	int[] tempCust = new int[clients.length+1];
	for(int i=0; i<clients.length; i++)
	    tempCust[i] = clients[i];
	tempCust[(clients.length)] = custID;
	clients = tempCust;	
 
	System.out.print("Enter development name: ");
	String developName = Keyboard.readString();
	Development projPurchase = new Development(developName);
	projPurchase.read(developName);
 
	System.out.println("What type of building do you want?: ");
	System.out.println("   [1] House");
	System.out.println("   [2] Small Office");
	System.out.println("   [3] Large Office");
	System.out.print("Enter choice: ");
	int typeBldg = Keyboard.readInt();
 
	Building[] tempBuild = new Building[edifices.length+1];
	for(int j=0; j<edifices.length; j++)
	    tempBuild[j] = edifices[j];
	if (typeBldg == 1)
	    tempBuild[(edifices.length)] = new House(custID);
	else if (typeBldg == 2)
	    tempBuild[(edifices.length)] = new SmallOffice(custID);
	else if (typeBldg == 3)
	    tempBuild[(edifices.length)] = new LargeOffice(custID);
	edifices = tempBuild;
 
	Pair gridVal = projPurchase.getDimensions();
	int gridX = gridVal.getX();
	int gridY = gridVal.getY();
 
	// map drawing
	for(int k=0; k <= gridX; k++)
	    System.out.print("*");
	System.out.println("*");
	for(int i = gridY-1; i >= 0; i--)
	{    
	    System.out.print("*");
	    for(int j=0; j < gridX; j++)
	    {
	    	GridLocation temp = projPurchase.getGridLocation(j, i);
	    	if (temp.canHoldBuilding() == false)
	    	    System.out.print(" ");
	    	else
	    	{    
       	    	    LotLocation Ltemp = (LotLocation) projPurchase.getGridLocation(j, i);
       	    	    if (Ltemp.getBuildingIndex() < 0)
       	    	    	System.out.print("Y");
       	    	    else
       	    	    	System.out.print(" ");
	    	}	
	    }
	    System.out.println("*");
	}
	for(int k=0; k <= gridX; k++)
	    System.out.print("*");
	System.out.println("*");	
 
	//call to add building
	System.out.println("Enter lower left corner of choice: ");
	System.out.print("   Enter x coordinate: ");
	int xLoc = Keyboard.readInt();
	System.out.print("   Enter y coordinate: ");
	int yLoc = Keyboard.readInt();
 
	projPurchase.addBuilding(edifices[(edifices.length-1)], xLoc, yLoc);	
	projPurchase.write(developName);
 
      // code added here in a later section of MP   
   }
 
 
 
 
   // *********************** View methods *************************
 
   private void viewCustomerHistory() 
   {
	printDevelopment();
      // code added here in a later section of MP
   }
 
 
 
   // **************** Administrator methods ***********************
 
   // administration
   //    - controls the selection and running of the program's 
   //         administration tools; when user chooses to quit
   //         the administration tools section of the program, 
   //         the program returns from this method back to the main
   //         menu control code 
   private void administration()
   {
      System.out.println("Administration Tools Menu");
 
      char menuChoice;
      boolean quittingNotWanted = true;
      do
      {
         menuChoice = getAdminMenuChoice();
 
         if (menuChoice == 'I')
            initializeDevelopment();
         else if (menuChoice == 'V')
            printDevelopment();
         else if (menuChoice == 'R')
            quittingNotWanted = false;
 
      } while (quittingNotWanted);
   }
 
 
   // getAdminMenuChoice
   //    - return value : a character representing a legal selection from
   //                       the administration tools menu 
   //    - prints out the administration tools menu and prompts the 
   //        user to make a selection from the menu. Reprompting will 
   //        occur as long as an illegal choice is entered. Once a legal
   //        choice is entered, the choice will be returned.  
   private char getAdminMenuChoice()
   {
      System.out.println("Please select one of the following options:");
      System.out.println("   [I] Initialize a Development");
      System.out.println("   [V] View Development Purchases");
      System.out.println("   [R] Return to Main Menu");
 
      char menuChoice;
      boolean menuChoiceIllegal = true;
      do
      {
         System.out.print("Enter choice: ");
         menuChoice = Keyboard.readChar();
         if ((menuChoice == 'I') || (menuChoice == 'V') || (menuChoice == 'R'))
            menuChoiceIllegal = false;
         else
            System.out.println("That is not a legal menu choice!");
         System.out.println();
      } while (menuChoiceIllegal);
 
      return menuChoice;
   }
 
 
   // initializeDevelopment
   //    - prompts the user for a database name and a land layout
   //         file name, and creates a new database with the land layout
   //         info and no buildings. If the user selects a database name of
   //         an already existing database, they will have the chance to
   //         change it if they want, or to keep the name they chose and
   //         thus clear the pre-existing database. Also, if the user
   //         enters a land layout file name that does not exist, the user
   //         will have the chance to select a new one or quit the 
   //         initialization process entirely. 
   private void initializeDevelopment()
   {
	boolean alreadyExist = false;
	int overlapPoint = -1;
        System.out.print("Enter name of database to initialize: ");
	String developFile = Keyboard.readString();
	do
	{
	    for(int i=0; i<developments.length; i++)
	    {
	        if (developments[i].equals(developFile))
	        {
		    alreadyExist = true;
		    overlapPoint = i;
		}
		else
		    alreadyExist = false;
	    }
 
	    if(!alreadyExist)
	    {
	    	String[] temp = new String[developments.length+1];
	    	for(int j=0; j<developments.length; j++)
	    	    temp[j] = developments[j];
	    	temp[(developments.length)] = developFile;
	    	developments = temp;
	    }
 
	    else
	    {
	    	char overWrite;
	    	System.out.print("Already Exists! clear it or select again? (C/S): ");
	    	overWrite = Keyboard.readChar();
 
	    	if (overWrite == 'C')
	    	{
	    	    	alreadyExist = false;
	    		//String[] temp = new String[developments.length+1];
	    		//for(int j=0; j<overlapPoint; j++)
	    	   	//    temp[j] = developments[j];
	    		//for(int j=overlapPoint; j<developments.length-1; j++)
	    		//    temp[j] = developments[(j+1)];
	    		//temp[(developments.length)] = developFile;
	    		//developments = temp;
 
	    	}
	    	else if (overWrite == 'S')
	    	{
	    		System.out.print("Enter name of database to initialize: ");
	    	    	developFile = Keyboard.readString();    
	    	}
	     }
	}while(alreadyExist);
 
 
 
 
	boolean fileExist = false;
 
	    System.out.print("Enter name of land layout description file: ");
	    String LandFile = Keyboard.readString();
 
	do{
 
	    File testFile = new File(LandFile);
	    if (testFile.exists())
	    {
	    	fileExist = true;
	    	Development Project = new Development(developFile);
	    	Project.importLandLayout(LandFile);
	    	Project.write(developFile);
	    }
	    else
	    {
	    	System.out.println("That database does not exist.");
	    	System.out.print("Select again or quit? (S/Q): ");
	    	if ('S'==Keyboard.readChar())
    	    	    {
    	    	    fileExist = false;
    	    	    System.out.print("Enter name of land layout description file: ");
		    LandFile = Keyboard.readString();
		    }
		else
	    	    fileExist = true;
	    }
	}while (!fileExist);
 
   }
 
 
 
 
   // printDevelopment
   //    - obtains a development project name from the user and 
   //       prints out the information about that development 
   //       project. The user will have the option of giving up
   //       trying to enter a name, if the name they've entered already
   //       is not the name of an existing project. 
   private void printDevelopment()
   {
	String namePrint;
	boolean alreadyExist = true;
 
	do
	{
	System.out.print("Enter name of database to print: ");
	namePrint = Keyboard.readString();
 
	    File testFile = new File(namePrint);
	    if (testFile.exists())
	    {
	    	alreadyExist = true;
	    	Development readProject = new Development(namePrint);
	    	readProject.read(namePrint);
	    	readProject.print();
	    }
	    else
	    {
	    	alreadyExist = false;
	    	System.out.println("The name of the project you entered does not exist.");	
	    	System.out.print("Select again or quit? (S/Q): ");
	    	char notQuit = Keyboard.readChar();
	    	if (notQuit!='S')
	    	    alreadyExist = true;
	    }
 
	}while(!alreadyExist);
 
 
      // you will write this code; most likely you will want some 
      //  helper methods too (they might perhaps be helper methods 
      //  also used by initializeDevelopment() as well, or maybe not.
      //  That is up to you. 
   }
 
 
 
   private boolean isAdministrator;
   private String[] developments;
   private int[] clients;
   private Building[] edifices;
}

Development.java

A class whose objects represent land development projects in progress

public class Development
{
   // Development
   //    - constructor 
   //    - parameters : name - name of this development project
   //    - initializes object to have parameter name and no
   //        buildings or area size
   public Development(String name) 
   {
      area = null;
      edifices = null;
      developmentName = name;
   }
 
 
 
   // getGridLocation
   //    - parameters : xVal - x coordinate of grid location
   //                 : yVal - y coordinate of grid location
   //    - return value : a reference to a grid location in this
   //        development
   //    - returns reference to the grid location at the parameter
   //       coordinate. No error checking is done at all.
   GridLocation getGridLocation(int xVal, int yVal)
   {
      return area[xVal][yVal];
   }
 
   Pair getDimensions()
   {
      return new Pair(area.length, area[0].length); 
   }
 
   // addBuilding
   //    - parameters : edifice - the building to be added
   //                 : xLoc - the x location of the building's lower left corner
   //                       (i.e. corner with smallest x and smallest y values)
   //                 : yLoc - the y location of the building's lower left corner
   //                       (i.e. cornewr with smallest x and smallest y values)
   //    - assumes that, for this building's dimensions, there are only
   //           LotLocation objects everywhere in the "area" GridLocation array
   //           for all the cells where this building should be added -- the
   //           lower left corner and any other cells. Inserts builing into
   //           development.
   public void addBuilding(Building edifice, int xLoc, int yLoc)
   {
	LotLocation tempLot = new LotLocation(xLoc, yLoc);
	int indexNum;
	if (edifices == null)
	    indexNum = 0;
	else
	    indexNum = this.edifices.length;
 
	Building[] tempBuild = new Building[indexNum+1];
	for(int j=0; j<indexNum; j++)
	    tempBuild[j] = this.edifices[j];
	tempBuild[indexNum] = edifice;
	this.edifices[] = tempBuild[];    
 
     	Pair Dim = edifice.getDimensions();
      	int bldgType = Dim.getY();
	((LotLocation) area[xLoc][yLoc]).setBuilding(edifice, indexNum);
	if (bldgType == 2 || bldgType == 4)
	{
	   ((LotLocation) area[xLoc+1][yLoc]).setBuilding(edifice, indexNum);
	   ((LotLocation) area[xLoc][yLoc+1]).setBuilding(edifice, indexNum);
	   ((LotLocation) area[xLoc+1][yLoc+1]).setBuilding(edifice, indexNum);
	}
	if (bldgType == 4)
	{
	   ((LotLocation) area[xLoc][yLoc+2]).setBuilding(edifice, indexNum);
	   ((LotLocation) area[xLoc][yLoc+3]).setBuilding(edifice, indexNum);
	   ((LotLocation) area[xLoc+1][yLoc+2]).setBuilding(edifice, indexNum);
	   ((LotLocation) area[xLoc+1][yLoc+3]).setBuilding(edifice, indexNum);
	}
 
   }
 
 
 
   // print
   //    - prints out details of every location in development grid
   public void print()
   {
      for (int i = 0; i < area.length; i++)
         for (int j = 0; j < area[0].length; j++)
            area[i][j].printDescription();
   }
 
 
 
   // importLandLayout
   //    - parameters : landFileName - the name of the file we 
   //                     want to import land information from 
   //    - imports information from a file with name equal to the
   //          parameter String; initializes development project
   //          using imported information.
   public void importLandLayout(String landFileName)  
   {
      ReadFile fileHandle = new ReadFile(landFileName);
      int numRows = ReadFileUtilities.readInt(fileHandle);
      int numCols = ReadFileUtilities.readInt(fileHandle);
 
      area = new GridLocation[numRows][numCols];
      for (int i = 0; i < numRows; i++)
         for (int j = 0; j < numCols; j++)
            area[i][j] = new LotLocation(i, j);
 
      int numInfo = ReadFileUtilities.readInt(fileHandle);
      for (int i = 1; i <= numInfo; i++)
      {
         char theKind = ReadFileUtilities.readChar(fileHandle);
         GridLocation temp = new GridLocation();
         if (theKind == 'W') 
            temp = new WaterLocation();
         else if (theKind == 'F')
            temp = new ForestLocation();
         else if (theKind == 'S')
            temp = new SandLocation();
         else if (theKind == 'G')
            temp = new GrassLocation();
 
         temp.read(fileHandle);
         area[temp.getXLocation()][temp.getYLocation()] = temp;
      }   
      fileHandle.closeFile();
   }
 
 
   // write
   //    - writes the information of this development into a 
   //      file with the approprate name -- specifically, the
   //      name of this development 
   public void write(String fileName)
   {
      WriteFile fileHandle = new WriteFile(fileName);
 
      if(edifices!=null)
      {
      	  fileHandle.println(edifices.length);
      	  int bldgType = 0;
      	  int CustID = 0;
      	  for(int i=0; i<edifices.length; i++)
      	  {
      	  	Pair Dim = edifices[i].getDimensions();
      	  	bldgType = Dim.getY();
 
      	  	if (bldgType == 1)
	   	    fileHandle.println("House");
	   	else if (bldgType == 2)
	   	    fileHandle.println("Small Office");
	   	else if (bldgType == 4)
	   	    fileHandle.println("Large Office");
 
	   	CustID = edifices[i].getCustomerID();
	   	fileHandle.println(CustID);
	  }
      }
      else
          fileHandle.println("0");
 
      fileHandle.println(area.length);
      fileHandle.println(area[0].length);
      GridLocation temp = new GridLocation();
      for(int i=0; i<area.length; i++)
      {
      	for(int j=0; j<area[0].length; j++)
      	{
      	    temp = getGridLocation(i,j);
      	    temp.write(fileHandle);
      	}
      }
      fileHandle.closeFile();
   } 
 
 
   // read
   //    - reads the information for this development from a file 
   //       named for this development
   public void read(String projectFile)
   {
	ReadFile fileHandle = new ReadFile(projectFile);
 
	int numBldg = ReadFileUtilities.readInt(fileHandle);
	Building[] edifices = new Building[numBldg];
 
	for(int i=0; i<edifices.length; i++)
	{
		String typeBldg = ReadFileUtilities.readString(fileHandle);
	   	int CustID = ReadFileUtilities.readInt(fileHandle);
	   	Building temp = null;
 
            	if (typeBldg.equals("House")==true)
                    temp = new House(CustID);	   	
            	else if (typeBldg.equals("Small Office")==true)
                    temp = new SmallOffice(CustID);	   	
            	else if (typeBldg.equals("Large Office")==true)
                    temp = new LargeOffice(CustID);	   	
 
	   	edifices[i] = temp;
	}
 
      	int numRows = ReadFileUtilities.readInt(fileHandle);
      	int numCols = ReadFileUtilities.readInt(fileHandle);
 
	area = new GridLocation[numRows][numCols];
 
	for(int i=1; i<=(numRows*numCols); i++)
	{
            String theKind = ReadFileUtilities.readString(fileHandle);
            GridLocation temp = new GridLocation();
            if (theKind.equals("WaterLocation")==true)
                temp = new WaterLocation();
            else if (theKind.equals("ForestLocation")==true)
            	temp = new ForestLocation();
            else if (theKind.equals("SandLocation")==true)
            	temp = new SandLocation();
            else if (theKind.equals("GrassLocation")==true)
            	temp = new GrassLocation();	
            else if (theKind.equals("LotLocation")==true)
            	temp = new LotLocation();
 
            temp.read(fileHandle);
 
            area[temp.getXLocation()][temp.getYLocation()] = temp;
        }
        fileHandle.closeFile();
 
   }
 
 
 
   private GridLocation[][] area;
   private String developmentName; 
   private Building[] edifices;
}


Comments