This is only one question. How can do I code this method in Java? I will include
ID: 649372 • Letter: T
Question
This is only one question. How can do I code this method in Java? I will include the other classes needed as well. Needs to be done with FileReader and Scanner only.
Here are the classes class Person, and class AddressBook.
PERSON
public class Person {
private String fullName;
private String phoneNumber;
private String email;
public Person(String fullName, String phoneNumber, String email)
throws ValidationException{
setFullName(fullName);
setPhoneNumber(phoneNumber);
setEmail(email);
}
public Person()
throws ValidationException{
this("Unknown","Unknown", "Unknown" );
}
public String getFullName(){
return fullName;
}
public void setFullName(String fullName)
throws ValidationException{
validateString(fullName, "Full Name", 50);
this.fullName = fullName;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber)
throws ValidationException{
validateString(phoneNumber, "Phone Number", 15);
this.phoneNumber = phoneNumber;
}
public String getEmail(){
return email;
}
public void setEmail(String email)
throws ValidationException{
validateString(email, "Email", 35);
this.email = email;
}
@Override
public String toString(){
return String.format("%s,%s,%s",
fullName, phoneNumber, email);
}
private static void validateString(String value, String fieldName, int maxLength)
throws ValidationException{
if(value == null || value.trim().length() == 0){
throw new ValidationException(
String.format("%s cannot be empty",
fieldName));
}
else if(value.length() > maxLength){
throw new ValidationException(
String.format("%s cannot exceed %d characters",
fieldName, maxLength));
}
else if(value.indexOf(',') > -1){
throw new ValidationException(
String.format("%s cannot conain a comma ','",
fieldName));
}
}
}
ADDRESSBOOK (METHOD NEEDING HELP WITH IS AT BOTTOM)
public class AddressBook {
/**
* Constant used in menu for adding a person
*/
private static final int ADD_PERSON = 1;
/**
* Constant used in menu for removing a person
*/
private static final int REMOVE_PERSON = 2;
/**
* Constant used in menu for sorting the persons by full name
*/
private static final int SORT_FULL_NAME = 3;
/**
* Constant used in menu for viewing the persons in the address book
*/
private static final int VIEW_PERSONS = 4;
/**
* Constant used in menu for exiting the program
*/
private static final int EXIT = 7;
/**
* Constant used in menu for saving the address book to the .txt file
*/
private static final int SAVE_ADDRESS_BOOK = 5;
/**
* Constant used in menu for loading the address book from the .txt file
*/
private static final int LOAD_ADDRESS_BOOK = 6;
/**
* Reference to the List that will store the objects
*/
private List<Person> persons;
/**
* Reference to Scanner used to interact with user
*/
private Scanner input;
/**
* Creates a new File that paths to the file in the computer
*/
File file = new File("C:UsersNickJavaWorkspaceAddressBook2.txt");
/**
* Reference to PrintWriter used to print ArrayList to txt file
*/
PrintWriter fw;
/**
* Reference to Formatter that formats the ArrayList when printing it
*/
Formatter fr;
/**
* Reference to FileReader that is used to read from the txt file
*/
FileReader f;
/**
* Reference to another Scanner being used in method loadAddressBook()
*/
Scanner read;
/**
* Reference to a String used in the while loop in method loadAddressBook()
*/
String line;
/**
* no-parameter Constructor
* instantiates the persons to an ArrayList
* also instantiates input to the Scanner
*/
public AddressBook(){
persons = new ArrayList<Person>();
input = new Scanner(System.in);
}
/**
* Main interaction logic, shows menu, reads in user option,
* calls methods to match users input option, and repeats in loop
* until user inputs exit option
*/
public void runAddressBook(){
int option = -1;
while(option != EXIT){
try{
showMenu();
option = input.nextInt();
input.nextLine(); // remove left over line terminator
switch(option){
case ADD_PERSON:
addPerson();
break;
case REMOVE_PERSON:
removePerson();
break;
case SORT_FULL_NAME:
sortByFullName();
break;
case VIEW_PERSONS:
viewPersons();
break;
case SAVE_ADDRESS_BOOK:
saveAddressBook();
break;
case LOAD_ADDRESS_BOOK:
loadAddressBook();
break;
case EXIT:
System.out.println("Program will exit");
break;
default:
System.out.println("Unrecognized command");
}
}
catch(InputMismatchException ex){
System.out.println("Please enter only numbers");
input.nextLine(); // clear out bad data from stream
}
}
}
/**
* Prints menu out for the user using the values in the constants
*/
private void showMenu(){
System.out.println(
String.format("%d Add person", ADD_PERSON));
System.out.println(
String.format("%d Remove person", REMOVE_PERSON));
System.out.println(
String.format("%d Sort by full name", SORT_FULL_NAME));
System.out.println(
String.format("%d View persons", VIEW_PERSONS));
System.out.println(
String.format("%d Save book", SAVE_ADDRESS_BOOK));
System.out.println(
String.format("%d load", LOAD_ADDRESS_BOOK));
System.out.println(
String.format("%d Exit program", EXIT));
}
/**
* Attempts to create a new person in the address book
* Program will ask user for name, number, and email
* and will then assign those values inputed to the fields
* of the Person, creating a new Person Object
* After it will add the new Person object into ArrayList persons
*/
private void addPerson(){
try{
System.out.print("Please enter full name ");
String fullName = input.nextLine();
System.out.print("Please enter phone number ");
String phoneNumber = input.nextLine();
System.out.print("Please enter email address ");
String emailAddress = input.nextLine();
persons.add(new Person(fullName, phoneNumber, emailAddress));
}
catch(ValidationException ex){
System.out.println(ex.getMessage());
}
}
/**
* Attempts to remove a person from the address book
* Searches the ArrayList first to check if it is empty
* If ArrayList has Person Object(s) in it, program will
* prompt the user to enter the index of the person
* User enters index and program will throw exception
* or successfully remove that person
*/
private void removePerson(){
try{
if(persons.size() <= 0){
System.out.println("Nothing to remove, persons list is empty");
}
else{
System.out.println("Enter index of person to remove");
int index = input.nextInt();
input.nextLine();
persons.remove(index);
}
}
catch(InputMismatchException ex){
System.out.println("Please enter only numbers");
}
catch(IndexOutOfBoundsException ex){
System.out.println("Invalid index number");
}
}
/**
* Attempts to sort the ArrayList by the persons full names
* Will check if ArrayList contains anything to sort
* Uses the comparator class to sort the Person objects
*/
private void sortByFullName(){
if(persons.size() <= 0){
System.out.println("Nothing to sort");
}
else{
Collections.sort(persons, PersonFullNameComparator.getInstance());
}
}
/**
* Attempts to print the persons that are in the ArrayList
* uses for loop to loop through the list and prints each
* index out into the console, if array is empty it
* displays message
*/
private void viewPersons(){
if(persons.size() > 0){
for(int index = 0; index < persons.size(); index++){
System.out.println(
String.format("Index: %d Person: %s",
index, persons.get(index)));
}
}
else{
System.out.println("No persons to display");
}
}
/**
* Attempts to save the current address book into a txt file on the computer
* instantiates the PrintWriter and Formatter being used
* loops through the ArrayList and prints it to the txt file
* flushes and closes the FileWriter
*/
private void saveAddressBook(){
try {
fw = new PrintWriter(file);
fr = new Formatter(fw);
for (int i = 0; i < persons.size(); i++) {
fw.print(persons.get(i));
fr.format("%n", persons.toString());
}
}catch (IOException e){
e.getMessage();
} finally {
fw.flush();
fw.close();
}
}
/**
* Attempts to load the saved address book from the txt file
* instantiates FileReader and Scanner to read txt file
* uses a while loop to print out the txt file
* closes scanner
*/
private void loadAddressBook(){
//CODE HERE
}
}
}
Explanation / Answer
The required code for the method loadAddressBook().
Here in-order to test the method, the program has been executed with a sample text file.
In you are executing this program, please check the File object before so that you can execute your text file.
private void loadAddressBook()
{
//declare a string array
String array[] = new String[3];
//declare a string variable
String line;
//Since working with files
//put the code in try catch block or else
//throw the Exception
try
{
//create object of the FileReader class by
//passing the file
f = new FileReader(file);
//create Scanner object by passing
//the FileReader object
read = new Scanner(f);
//check whether the file exists or not
if (file.exists())
{
//if exists read the data from the text file
//until it reaches the end of the text file
while (read.hasNextLine())
{
//get the line from the text file
//and store it in the string variable line.
line = read.nextLine();
//now split the line at the specified delimiter
//and store the array values into array
array = line.split(",");
//either place the each value into new String variables
//or one can pass the array directly as parameters
//to the Person class reference.
String fullName = array[0];
String phoneNumber = array[1];
String emailAddress = array[2];
persons.add(new Person(fullName, phoneNumber, emailAddress));
}
}
else
{
System.out.println("Unable to open the file.");
}
f.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Program code:
import java.io.*;
import java.util.*;
public class AddressBook
{
/**
* Constant used in menu for adding a person
*/
private static final int ADD_PERSON = 1;
/**
* Constant used in menu for removing a person
*/
private static final int REMOVE_PERSON = 2;
/**
* Constant used in menu for sorting the persons by full name
*/
private static final int SORT_FULL_NAME = 3;
/**
* Constant used in menu for viewing the persons in the address book
*/
private static final int VIEW_PERSONS = 4;
/**
* Constant used in menu for exiting the program
*/
private static final int EXIT = 7;
/**
* Constant used in menu for saving the address book to the .txt file
*/
private static final int SAVE_ADDRESS_BOOK = 5;
/**
* Constant used in menu for loading the address book from the .txt file
*/
private static final int LOAD_ADDRESS_BOOK = 6;
/**
* Reference to the List that will store the objects
*/
private ArrayList<Person> persons;
/**
* Reference to Scanner used to interact with user
*/
private Scanner input;
/**
* Creates a new File that paths to the file in the computer
*/
// File file = new
// File("C:\Users\Nick\JavaWorkspace\AddressBook2.txt");
File file = new File("PersonAddressBook.txt");
/**
* Reference to PrintWriter used to print ArrayList to txt file
*/
PrintWriter fw;
/**
* Reference to Formatter that formats the ArrayList when printing it
*/
Formatter fr;
/**
* Reference to FileReader that is used to read from the txt file
*/
FileReader f;
/**
* Reference to another Scanner being used in method loadAddressBook()
*/
Scanner read;
/**
* Reference to a String used in the while loop in method loadAddressBook()
*/
String line;
/**
* no-parameter Constructor instantiates the persons to an ArrayList also
* instantiates input to the Scanner
*/
public AddressBook()
{
persons = new ArrayList<Person>();
input = new Scanner(System.in);
}
/**
* Main interaction logic, shows menu, reads in user option, calls methods
* to match users input option, and repeats in loop until user inputs exit
* option
*/
public void runAddressBook()
{
int option = -1;
while (option != EXIT)
{
try
{
showMenu();
option = input.nextInt();
input.nextLine(); // remove left over line terminator
switch (option)
{
case ADD_PERSON:
addPerson();
break;
case REMOVE_PERSON:
removePerson();
break;
case SORT_FULL_NAME:
sortByFullName();
break;
case VIEW_PERSONS:
viewPersons();
break;
case SAVE_ADDRESS_BOOK:
saveAddressBook();
break;
case LOAD_ADDRESS_BOOK:
loadAddressBook();
break;
case EXIT:
System.out.println("Program will exit");
break;
default:
System.out.println("Unrecognized command");
}
} catch (InputMismatchException ex)
{
System.out.println("Please enter only numbers");
input.nextLine(); // clear out bad data from stream
}
}
}
/**
* Prints menu out for the user using the values in the constants
*/
private void showMenu()
{
System.out.println(String.format("%d Add person", ADD_PERSON));
System.out.println(String.format("%d Remove person", REMOVE_PERSON));
System.out.println(String.format("%d Sort by full name", SORT_FULL_NAME));
System.out.println(String.format("%d View persons", VIEW_PERSONS));
System.out.println(String.format("%d Save book", SAVE_ADDRESS_BOOK));
System.out.println(String.format("%d load", LOAD_ADDRESS_BOOK));
System.out.println(String.format("%d Exit program", EXIT));
}
/**
* Attempts to create a new person in the address book Program will ask
* user for name, number, and email and will then assign those values
* inputed to the fields of the Person, creating a new Person Object After
* it will add the new Person object into ArrayList persons
*/
private void addPerson()
{
try
{
System.out.print("Please enter full name ");
String fullName = input.nextLine();
System.out.print("Please enter phone number ");
String phoneNumber = input.nextLine();
System.out.print("Please enter email address ");
String emailAddress = input.nextLine();
persons.add(new Person(fullName, phoneNumber, emailAddress));
} catch (ValidationException ex)
{
System.out.println(ex.getMessage());
}
}
/**
* Attempts to remove a person from the address book Searches the ArrayList
* first to check if it is empty If ArrayList has Person Object(s) in it,
* program will prompt the user to enter the index of the person User
* enters index and program will throw exception or successfully remove
* that person
*/
private void removePerson()
{
try
{
if (persons.size() <= 0)
{
System.out.println("Nothing to remove, persons list is empty");
} else
{
System.out.println("Enter index of person to remove");
int index = input.nextInt();
input.nextLine();
persons.remove(index);
}
} catch (InputMismatchException ex)
{
System.out.println("Please enter only numbers");
} catch (IndexOutOfBoundsException ex)
{
System.out.println("Invalid index number");
}
}
/**
* Attempts to sort the ArrayList by the persons full names Will check if
* ArrayList contains anything to sort Uses the comparator class to sort
* the Person objects
*/
private void sortByFullName()
{
if (persons.size() <= 0)
{
System.out.println("Nothing to sort");
} else
{
Collections.sort(persons, PersonFullNameComparator());
}
}
private static Comparator<Person> PersonFullNameComparator()
{
return new Comparator<Person>()
{
@Override
public int compare(Person x, Person y)
{
return x.getFullName().compareTo(y.getFullName());
}
};
}
/**
* Attempts to print the persons that are in the ArrayList uses for loop to
* loop through the list and prints each index out into the console, if
* array is empty it displays message
*/
private void viewPersons()
{
if (persons.size() > 0)
{
for (int index = 0; index < persons.size(); index++)
{
System.out.println(String.format("Index: %d Person: %s", index, persons
.get(index)));
}
} else
{
System.out.println("No persons to display");
}
}
/**
* Attempts to save the current address book into a txt file on the
* computer instantiates the PrintWriter and Formatter being used loops
* through the ArrayList and prints it to the txt file flushes and closes
* the FileWriter
*/
private void saveAddressBook()
{
try
{
fw = new PrintWriter(file);
fr = new Formatter(fw);
for (int i = 0; i < persons.size(); i++)
{
fw.print(persons.get(i));
fr.format("%n", persons.toString());
}
} catch (IOException e)
{
e.getMessage();
} finally
{
fw.flush();
fw.close();
}
}
/**
* Attempts to load the saved address book from the txt file instantiates
* FileReader and Scanner to read txt file uses a while loop to print out
* the txt file closes scanner
*/
private void loadAddressBook()
{
//declare a string array
String array[] = new String[3];
//declare a string variable
String line;
//Since working with files
//put the code in try catch block or else
//throw the Exception
try
{
//create object of the FileReader class by
//passing the file
f = new FileReader(file);
//create Scanner object by passing
//the FileReader object
read = new Scanner(f);
//check whether the file exists or not
if (file.exists())
{
//if exists read the data from the text file
//until it reaches the end of the text file
while (read.hasNextLine())
{
//get the line from the text file
//and store it in the string variable line.
line = read.nextLine();
//now split the line at the specified delimiter
//and store the array values into array
array = line.split(",");
//either place the each value into new String variables
//or one can pass the array directly as parameters
//to the Person class reference.
String fullName = array[0];
String phoneNumber = array[1];
String emailAddress = array[2];
persons.add(new Person(fullName, phoneNumber, emailAddress));
}
}
else
{
System.out.println("Unable to open the file.");
}
f.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public class Person
{
private String fullName;
private String phoneNumber;
private String email;
public Person(String fullName, String phoneNumber, String email) throws ValidationException
{
setFullName(fullName);
setPhoneNumber(phoneNumber);
setEmail(email);
}
public Person() throws ValidationException
{
this("Unknown", "Unknown", "Unknown");
}
public String getFullName()
{
return fullName;
}
public void setFullName(String fullName) throws ValidationException
{
validateString(fullName, "Full Name", 50);
this.fullName = fullName;
}
public String getPhoneNumber()
{
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) throws ValidationException
{
validateString(phoneNumber, "Phone Number", 15);
this.phoneNumber = phoneNumber;
}
public String getEmail()
{
return email;
}
public void setEmail(String email) throws ValidationException
{
validateString(email, "Email", 35);
this.email = email;
}
@Override
public String toString()
{
return String.format("%s,%s,%s", fullName, phoneNumber, email);
}
private static void validateString(String value, String fieldName, int maxLength)
throws ValidationException
{
if (value == null || value.trim().length() == 0)
{
throw new ValidationException(String.format("%s cannot be empty", fieldName));
} else if (value.length() > maxLength)
{
throw new ValidationException(String.format("%s cannot exceed %d characters",
fieldName, maxLength));
} else if (value.indexOf(',') > -1)
{
throw new ValidationException(String.format("%s cannot conain a comma ','",
fieldName));
}
}
}
//To test the AddressBook the class //AddressBookImplementation is being used here
public class AddressBookImplementation
{
public static void main(String args[])
{
AddressBook ab = new AddressBook();
ab.runAddressBook();
}
}
Sample TextFile: PersonAddressBook.txt
Kelvin,123-986512,kelvin@gmail.com
John,123-456897,john.12@gmail.com
Andy,129-123456,andy@hotmail.com
Linda,1234-256487,linda.lin@facebook.com
Sample Output:
1 Add person
2 Remove person
3 Sort by full name
4 View persons
5 Save book
6 load
7 Exit program
6
1 Add person
2 Remove person
3 Sort by full name
4 View persons
5 Save book
6 load
7 Exit program
4
Index: 0 Person: Kelvin,123-986512,kelvin@gmail.com
Index: 1 Person: John,123-456897,john.12@gmail.com
Index: 2 Person: Andy,129-123456,andy@hotmail.com
Index: 3 Person: Linda,1234-256487,linda.lin@facebook.com
1 Add person
2 Remove person
3 Sort by full name
4 View persons
5 Save book
6 load
7 Exit program
3
1 Add person
2 Remove person
3 Sort by full name
4 View persons
5 Save book
6 load
7 Exit program
4
Index: 0 Person: Andy,129-123456,andy@hotmail.com
Index: 1 Person: John,123-456897,john.12@gmail.com
Index: 2 Person: Kelvin,123-986512,kelvin@gmail.com
Index: 3 Person: Linda,1234-256487,linda.lin@facebook.com
1 Add person
2 Remove person
3 Sort by full name
4 View persons
5 Save book
6 load
7 Exit program
7
Program will exit
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.