Here is the driver file
import java.util.Scanner;
/** Driver to present a main menu for testing all methods within
* PersonFileWrapper.
*/
public class Chp10Driver {
public static void main(String[] args) {
PersonFileWrapper pfw = new PersonFileWrapper();
int menuChoice = -1;
do {
menuChoice = retrieveMenuSelection(pfw.getNumEntries());
switch(menuChoice) {
case 1:
pfw.addPerson();
break;
case 2:
pfw.retrievePerson();
break;
case 3:
pfw.deletePerson();
break;
case 4:
pfw.viewAll();
break;
case 5:
pfw.saveData();
break;
case 6:
pfw.loadData();
break;
case 0:
System.out.println("Thank you for playing!");
System.exit(0);
break;
default:
// do nothing
System.out.println("Invalid entry, please enter a valid menu selection.\n");
}
} while (0 != menuChoice);
}
/** Method to create a String that will be displayed for the user to
* make their menu selections.
* @param numPersons
* @return Menu String
*/
protected static String getMenu(int numPersons) {
return "Person Manipulation Menu (" + numPersons +
" entries of " + PersonFileWrapper.MAXRECORDS + " max):\n" +
"1 = Add person \n" +
"2 = Retrieve person \n" +
"3 = Delete person \n" +
"4 = View all person(s) \n" +
"5 = Save data to file, " + PersonFileWrapper.FILENAME + "\n" +
"6 = Load data from disk \n" +
"0 = Quit \n" +
"Please enter your menu selection now.\n";
}
/** Method to retrieve user menu selection.
* @param numPersons
* @return Integer menu selection, -1 if the user made no selection or
* an invalid one.
*/
protected static int retrieveMenuSelection(int numPersons) {
// initialize the return value as MAXVALUE
int retVal = -1;
System.out.println(getMenu(numPersons));
Scanner keyboard = new Scanner(System.in);
String line = null;
do {
try {
line = keyboard.nextLine();
retVal = Integer.parseInt(line);
} catch(Exception e) {
System.out.println("Invalid entry, please enter a valid menu selection.\n");
retVal = -1;
}
} while(retVal < 0);
return retVal;
}
}
Here is the PersonWrapper File
import java.io.File;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.util.Scanner;
/** Class used to execute load, search, delete and view menu actions on a
* Person[].
*/
public class PersonFileWrapper {
public static final String FILENAME = "person.dat";
public static final int MAXRECORDS = 15;
private Person[] data;
private int numEntries = 0;
/** Constructor that creates the data array that will eventually contain
* the Person records. This constructor immediately tries to load
* from the local directory file, FILENAME. If it cannot find that
* file, the data[] is initialized as an empty array of size 15.
*/
public PersonFileWrapper() {
data = new Person[MAXRECORDS];
// Load file from disk if it exists, otherwise initialize to blank
File fileObject = new File(FILENAME);
if (fileObject.exists()) {
loadData();
}
}
/** Method to write all Person objects contained within data[] to a
* file specified by FILENAME.
*/
public void saveData() {
// ITP 220 - implement this method
// when finished, print the number of records written
}
/** Method to read all Person objects from the file specified by FILENAME.
* This method overwrites any existing entries in data[].
*/
public void loadData() {
// ITP 220 - implement this method
// Load should overwrite existing data[] entries and update numEntries
}
/** Method that uses Scanner to prompt the user for Person data to use to
* create Person objects added to data[]. This method should attempt
* to fill the first empty data[] index and should notify the user
* when invalid data is entered.
*/
public void addPerson() {
// ITP 220 - implement this method
// prompt for all Person data and validate entries
// fill the first available index position
}
/** Method to print and retrieve the index of a retrieved Person object.
* If no Person was not found with the matching search String in ANY of
* its variables, this method prints a message and returns -1.
* @return int[] - Indices within data[] of matching Person objects
*/
public int[] retrievePerson() {
Scanner keyboard = new Scanner(System.in);
System.out.println(
"Please enter a search String (followed by the Enter key):\n");
String search = keyboard.nextLine();
while(search == null || search.trim().length() == 0) {
System.out.println("Invalid entry, please enter a search String of one or more characters.");
search = keyboard.nextLine();
}
System.out.println("Trying to retrieve person " + search);
// initialize returned int[] to a maximum of numEntries indices
int[] indices = new int[numEntries];
// ITP 220 - complete the retrieval part of this method updating the
// int[] with matching indices and printing information on all Person
// Objects found
return indices;
}
/** Method to prompt the user for information on which Person to delete.
* This method should make use of retrievePerson and should allow the
* user to remove one or more Person objects.
*/
public void deletePerson() {
// ITP 220 - complete this method
// Prompt the user before removing one or more Persons based on
// their search criteria
}
/** Method to print information for all Person objects within data[].
*/
public void viewAll() {
// ITP 220 - complete this method
}
/** Accessor method for the number of Person objects within data[].
* This number should never include NULL Person entries.
*/
public int getNumEntries() {
return numEntries;
}
}
Here is the Person File
/** Person.java
* This class defines a person with attributes for name and birth/death
* dates.
* As with a real Person, there must always be a date of birth, and if
* the Person has a date of death, then the date of death is equal to
* or later than the date of birth.
*/
import java.io.Serializable;
public class Person implements Serializable {
public class Date implements Comparable, Cloneable {
/** Static Array of valid months (in month index order) */
private final String[] VALID_MONTHS = new String[] {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
/** Month, as a String, initially NULL */
private String month;
private int day = 0; // initially invalid
private int year = 0; // initially invalid
public Object clone() {
try
{
return super.clone();
}
catch(CloneNotSupportedException e)
{
return null; // To keep the compiler happy
}
}
public int compareTo(Object other) {
Date otherDate = (Date)other;
if (this.precedes(otherDate))
return -1;
else if (this.equals(otherDate))
return 0;
return 1;
}
/** Empty constructor.
* Sets default month, day and year to Jan. 1, 2000
*/
public Date( ) {
month = VALID_MONTHS[0];
day = 1;
year = 2000;
}
/** Argument constructor.
* @param monthInt - month as an int
* @param day
* @param year
*/
public Date(int monthInt, int day, int year) {
setDate(monthInt, day, year);
}
/** Argument constructor.
* @param monthString - month as a String
* @param day
* @param year
*/
public Date(String monthString, int day, int year) {
setDate(monthString, day, year);
}
/** Argument constructor. Sets Date to the first day of the year.
* @param year - initialize this Date to the first day of this year.
*/
public Date(int year) {
setDate(year);
}
/** Argument constructor.
* @param aDate - Date to base this new Date instance on.
* If null, this date will have no valid month set.
*/
public Date(Date aDate) {
if (aDate != null) {
month = aDate.getMonth();
day = aDate.getDay();
year = aDate.getYear();
}
}
/** Method to set this Date to the first day of the given year.
* @param year - initialize this Date to the first day of this year
* @return boolean - TRUE if year was valid
*/
public boolean setDate(int year) {
return setDate(VALID_MONTHS[0], 1, year);
}
/** Method to set the attributes for this Date instance.
* @param monthInt - month as an int
* @param day
* @param year
* @return boolean - TRUE if date entries were valid
*/
public boolean setDate(int monthInt, int day, int year) {
return setDate(getMonthString(monthInt), day, year);
}
/** Method to set the attributes for this Date instance.
* @param monthString - month as a String
* @param day
* @param year
* @return boolean - TRUE if date was valid
*/
public boolean setDate(String monthString, int day, int year) {
if (dateOK(monthString, day, year)) {
month = monthString;
this.day = day;
this.year = year;
return true;
}
return false;
}
/** Method to validate and set the year for this Date
* @param year - int
*/
public void setYear(int year) {
if(yearOk(year)) {
this.year = year;
}
}
/** Method to validate the year
* @param year - int
* @return boolean - TRUE if year was valid
*/
public boolean yearOk(int year) {
if (year >= 1900);
return true;
}
/** Method to validate and set the month for this Date
* @param monthIndex - int - month index
* @return boolean - TRUE if month was valid
*/
public void setMonth(int monthIndex) {
String monthStr = getMonthString(monthIndex);
if (monthStr != null) {
month = monthStr;
}
}
/** Method to set the day for this Date after checking that it is
* valid for the month that is currently set.
* @param day - valid day
*/
public void setDay(int day) {
if(dayOk(day)) {
this.day = day;
}
}
/** Method to validate the day of a month
* @param day - int
* @return boolean - TRUE if day was valid
*/
public boolean dayOk(int day) {
return dayOk(day, month);
}
/** Method to validate the day of a month
* @param day - int
* @param month - month to validate this day against
* @return boolean - TRUE if day was valid
*/
public boolean dayOk(int day, String month) {
return ((day >= 1) && (day <= 31)) &&
((getMonthIndex(month) >= 1) && (getMonthIndex(month) <= 12)
|| (getMonthIndex(month) == 2) && ((day >= 1) && (day <= 28)));
}
/** Equals method to compare this Date to another Object.
* @param other - Object being compared to 'this'
* @return - TRUE if other contains the same information as 'this'
*/
public boolean equals(Date otherDate) {
if (otherDate == null) {
return false;
} else {
// check MONTH String
if((month == null && otherDate.getMonth() != null) ||
((month != null) && !month.equals(otherDate.getMonth())) ) {
return false;
}
// check day and year ints
return (day == otherDate.getDay()) &&
(year == otherDate.getYear());
}
}
/** Method to determine if this Date precedes another one.
* @param d4 - Date being compared
* @return boolean - TRUE if this Date precedes otherDate
*/
public boolean precedes(Date d4) {
if(d4 == null)
return true;
// check the conditions of precedes in order, returning false when
// 1. Year is > otherDate's year
// 2. Year = otherDate's year, but month > otherDate's month
// 3. Year and month = otherDate's, but day > otherDates's day
return (year < d4.getYear()) ||
((year == d4.getYear()) &&
(getMonthIndex(month) < d4.getMonthIndex(d4.getMonth()))) ||
((year == d4.getYear()) &&
(getMonthIndex(month) == d4.getMonthIndex(d4.getMonth()) &&
(day < d4.getDay())));
}
/** Method to return whether all 3 parameters create a valid Date
* @param monthInt
* @param dayInt
* @param yearInt
* @return boolean - TRUE if Date is valid
*/
private boolean dateOK(int monthInt, int dayInt, int yearInt) {
return dateOK(getMonthString(monthInt), dayInt, yearInt);
}
/** Method to return whether all 3 parameters create a valid Date
* @param monthString
* @param dayInt
* @param yearInt
* @return boolean - TRUE if Date is valid
*/
boolean dateOK(String monthString, int dayInt, int yearInt) {
return (monthOk(monthString) && dayOk(dayInt, monthString) &&
yearOk(yearInt));
}
/** Internal method to validate a month String.
* @param month - month String to validate.
* @return boolean - TRUE if the month is valid
*/
private boolean monthOk(String month) {
if(month == null) {
return false;
}
return getMonthIndex(month) >= 0;
}
/** Internal method to convert a month index to its corresponding
* month String.
* @param monthNumber - month index where month=1 is January and month=12 is December
* @return String - month as a String
*/
private String getMonthString(int monthNumber) {
if(monthNumber > 0 && monthNumber <= VALID_MONTHS.length) {
// retrieve the month found at monthNumber-1 (1 for the
// 0 index position (not a valid month index)
return VALID_MONTHS[monthNumber-1];
}
return null;
}
/** Internal method to convert a month String to its corresponding
* month index.
* @param monthStr - month String
* @return int - gets month index for the current month, 0 indicates
* that a valid month has not been set.
*/
public int getMonthIndex(String monthStr) {
if (monthStr.equals("January"))
return 1;
else if (monthStr.equals("February"))
return 2;
else if (monthStr.equals("March"))
return 3;
else if (monthStr.equals("April"))
return 4;
else if (monthStr.equals("May"))
return 5;
else if (monthStr.equals("June"))
return 6;
else if (monthStr.equals("July"))
return 7;
else if (monthStr.equals("August"))
return 8;
else if (monthStr.equals("September"))
return 9;
else if (monthStr.equals("October"))
return 10;
else if (monthStr.equals("November"))
return 11;
else if (monthStr.equals("December"))
return 12;
return 0;
}
public int getDay( ) {
return day;
}
public int getYear( ) {
return year;
}
public String getMonth() {
return month;
}
public String toString( ) {
return (month + " " + day + ", " + year);
}
}
private String name;
private Date born;
private Date died; // null indicates still alive.
public Object clone() {
try
{
return super.clone();
}
catch(CloneNotSupportedException e)
{
return null; // To keep the compiler happy
}
}
public Person(){
}
/** Argument constructor to create a Person (with no death date).
* @param initialName
* @param birthMonth - int
* @param birthDay - int
* @param birthYear - int
*/
public Person(String initialName, int birthMonth, int birthDay,
int birthYear) {
this.name = initialName;
this.born = new Date (birthMonth, birthDay, birthYear);
}
/** Argument constructor to create a Person (with no death date).
* @param initialName
* @param birthMonth - String
* @param birthDay - int
* @param birthYear - int
*/
public Person(String initialName, String birthMonth, int birthDay,
int birthYear) {
this.name = initialName;
this.born = new Date (birthMonth, birthDay, birthYear);
}
/** Argument constructor to create a Person (with a death date).
* @param initialName
* @param birthMonth - String
* @param birthDay - int
* @param birthYear - int
* @param deathMonth - String
* @param deathDay - int
* @param deathYear - int
*/
public Person(String initialName, String birthMonth, int birthDay,
int birthYear, String deathMonth, int deathDay, int deathYear) {
name = initialName;
born = new Date (birthMonth, birthDay, birthYear);
died = new Date (deathMonth, deathDay, deathYear);
}
/** Argument constructor to create a Person (with a death date).
* @param initialName
* @param birthMonth - int
* @param birthDay - int
* @param birthYear - int
* @param deathMonth - int
* @param deathDay - int
* @param deathYear - int
*/
public Person(String initialName, int birthMonth, int birthDay,
int birthYear, int deathMonth, int deathDay, int deathYear) {
name = initialName;
born = new Date (birthMonth, birthDay, birthYear);
died = new Date (deathMonth, deathDay, deathYear);
}
/** Argument constructor to create a Person.
* @param initialName
* @param birthDate
* @param deathDate
*/
public Person(String initialName, Date birthDate, Date deathDate) {
set(initialName, birthDate, deathDate);
}
/** Copy constructor.
* @param original - object (Person) whose attributes will be used
* to create this new Person.
*/
public Person(Person original) {
if (original != null) {
set(original.getName(), original.getBirthDate(),
original.getDeathDate());
}
}
/** Method to set all attributes of this Person from supplied
* arguments.
* @param initialName
* @param birthDate
* @param deathDate
*/
public void set(String newName, Date birthDate, Date deathDate) {
if (consistent(birthDate, deathDate)) {
name = newName;
born = new Date(birthDate);
if(deathDate == null) {
died = null;
} else {
died = new Date(deathDate);
}
}
}
/** Method to display this Person't attributes in a user-friendly
* printout.
*/
public String toString( ) {
return name + ", " + born + "-" + died;
}
/** Method to determine whether this Person has the same attributes
* as the passed Person.
* @param otherPerson - Person being compared to this
*/
public boolean equals(Person otherPerson) {
if (otherPerson == null) {
return false;
} else {
// check NAME
if((name == null && otherPerson.getName() != null) ||
(name != null) && !name.equals(otherPerson.getName()) ) {
return false;
}
// check Dates
return
datesMatch(getBirthDate(), otherPerson.getBirthDate()) &&
datesMatch(getDeathDate(), otherPerson.getDeathDate());
}
}
/** Method to match date1 and date2, which must either be the same
* dates or both null.
*/
private boolean datesMatch(Date date1, Date date2) {
if (date1 == null) {
return (date2 == null); // true if date2 is also null
} else if (date2 == null) { // start tests where date1 is not null
return false;
} else {
return(date1.equals(date2));
}
}
/** Method that verifies whether the supplied birth/death dates are
* consistent with each other. Rules are:
* 1. Birth Date must not be null
* 2. If death date is not null, birthDate must come before or
* be equal to the deathDate.
*/
private boolean consistent(Date birthDate, Date deathDate) {
if (birthDate == null) {
return false;
} else if (!birthDate.dateOK(birthDate.getMonth(),
birthDate.getDay(), birthDate.getYear())) {
return false;
} else if (deathDate == null) {
return true; // nothing else to check if it makes it here
} else if (!deathDate.dateOK(deathDate.getMonth(),
deathDate.getDay(), deathDate.getYear())) {
return false;
}
return birthDate.compareTo(deathDate) <= 0;
}
/** Method to set birth date. Before setting it to newDate,
* checks that it is valid with the existing death date.
*/
public void setBirthDate(Date newDate) {
if (consistent(newDate, died)) {
if (newDate == null) {
born = null;
} else {
born = new Date(newDate);
}
}
}
/** Method to set death date. Before setting it to newDate,
* checks that it is valid with the existing birth date.
*/
public void setDeathDate(Date newDate) {
if (consistent(born, newDate)) {
if (newDate == null) {
died = null;
} else {
died = new Date(newDate);
}
}
}
/** Method to reset only the birth year.
* This method does nothing if date of birth is NULL.
*/
public void setBirthYear(int newYear) {
if (born == null) {
return;
}
// set birth year by creating a new Date and updating its
// year, then validate this as a possible birth date before
// setting = born
Date updatedDate = new Date(born);
updatedDate.setYear(newYear);
if (consistent(updatedDate, died)) {
born = updatedDate;
}
}
/** Method to reset only the death year.
* This method does nothing if date of death is NULL.
*/
public void setDeathYear(int newYear) {
if (died == null) {
return;
}
// set death year by creating a new Date and updating its
// year, then validate this as a possible death date before
// setting = died
Date updatedDate = new Date(died);
updatedDate.setYear(newYear);
if (consistent(born, updatedDate)) {
died = updatedDate;
}
}
public String getName( ) {
return name;
}
public void setName(String newName) {
name = newName;
}
public Date getBirthDate( ) {
if(born != null) {
return new Date(born);
} else {
return null;
}
}
public Date getDeathDate( ) {
if(died != null) {
return new Date(died);
} else {
return null;
}
}
}

New Topic/Question
Reply



MultiQuote





|