Question

In: Computer Science

JAVA FILE PROGRAM Write a contacts database program that presents the user with a menu that...

JAVA FILE PROGRAM

Write a contacts database program that presents the user with a menu that allows the user to select between the following options:

  • Save a contact.
  • Search for a contact.
  • Print all contacts out to the screen.
  • Quit

If the user selects the first option, the user is prompted to enter a person's name and phone number which will get saved at the end of a file named contacts.txt.
If the user selects the second option, the program prompts the user asking for the name of the contact. It then searches the contacts.txt for a matching name. If found, it displays the phone number on the screen. If not found, it will display an appropriate error message.
If the user selects the third option, the program displays all contacts stored in contacts.txt in a neat table.
The program is menu driven and will repeat presenting the menu and processing choices until the user selects the fourth option to quit.
If the user selects an invalid option, an appropriate error message should be displayed.
If the user selects to print all contacts to the screen with no stored contacts, an appropriate error message should be displayed.

You may use message dialogs or make it a purely console-based application

Solutions

Expert Solution

Contact.java

public class Contact {
private String name, number;
  
public Contact()
{
this.name = "";
this.number = "";
}

public Contact(String name, String number) {
this.name = name;
this.number = number;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}
  
public String toString(){ return ("Name: " + this.name + ", Number: " + this.number); }
}

ContactDB.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class ContactDB {
  
private ArrayList<Contact> contacts;
  
public ContactDB()
{
this.contacts = new ArrayList<>();
}
  
public void readContactFile(String fileName)
{
Scanner fileReader;
int count = 0;
try
{
fileReader = new Scanner(new File(fileName));
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine().trim();
String[] data = line.split(",");
this.contacts.add(new Contact(data[0], data[1]));
count++;
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println("Could not locate file: " + fileName);
System.exit(0);
}
System.out.println("Finished reading " + count + " contacts.\n");
}
  
public void saveContact(String fileName)
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the contact name: ");
String name = sc.nextLine().trim();
while(name.length() < 0)
{
System.out.print("\nPlease enter a valid contact name: ");
name = sc.nextLine().trim();
}
System.out.print("Enter the contact number: ");
String number = sc.nextLine().trim();
while(number.length() < 0)
{
System.out.print("\nPlease enter a valid contact number: ");
number = sc.nextLine().trim();
}
  
this.contacts.add(new Contact(name, number));
writeContacts(fileName);
System.out.println(name + " has successfully been saved to contacts!\n");
}
  
private void writeContacts(String fileName)
{
FileWriter fw;
PrintWriter pw;
try
{
fw = new FileWriter(new File(fileName));
pw = new PrintWriter(fw);
  
for(Contact con : contacts)
{
pw.write(con.getName() + "," + con.getNumber() + System.lineSeparator());
}
  
pw.flush();
fw.close();
pw.close();
}catch(IOException ioe){
System.out.println("Error in writing to file: " + fileName);
System.exit(0);
}
}
  
public void searchContact()
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter a contact name to search: ");
String name = sc.nextLine().trim();
  
boolean found = false;
int index = -1;
for(int i = 0; i < contacts.size(); i++)
{
if(contacts.get(i).getName().equalsIgnoreCase(name))
{
found = true;
index = i;
break;
}
}
if(!found)
System.out.println("\nNo matches found for contact name: " + name + ".\n");
else
System.out.println("\nMatch found:\n" + contacts.get(index).toString());
}
  
public void displayAllContacts()
{
System.out.println("ALL CONTACTS\n------------");
System.out.printf("%10s %10s %15s\n", "SL. No.", "Contact Name", "Contact Number");
int i = 0;
for(Contact con : contacts)
{
i++;
System.out.printf("%10d %10s %15s\n", i, con.getName(), con.getNumber());
}
System.out.println();
}
}

ContactDBTest.java (Driver class)

import java.util.Scanner;

public class ContactDBTest {
  
private static final String FILENAME = "contacts.txt";
  
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ContactDB db = new ContactDB();
  
// read contacts from the file and populate the list
db.readContactFile(FILENAME);
  
// user menu
int choice;
do
{
printMenu();
choice = Integer.parseInt(sc.nextLine().trim());
switch(choice)
{
case 1:
{
db.saveContact(FILENAME);
break;
}
  
case 2:
{
db.searchContact();
break;
}
  
case 3:
{
db.displayAllContacts();
break;
}
  
case 4:
{
System.out.println("\nThank you!\nGood Bye!\n");
System.exit(0);
}
  
default:
System.out.println("\nInvalid choice!\n");
}
}while(choice != 4);
}
  
private static void printMenu()
{
System.out.print("1. Save a contact\n"
+ "2. Search for a contact\n"
+ "3. Display all contacts\n"
+ "4. Quit\n"
+ "Enter your choice: ");
}
}

******************************************************************** SCREENSHOT *******************************************************

FILE (contacts.txt - This file needs to be created before running the code, data in the file may vary)

CONSOLE OUTPUT:


Related Solutions

in java Write a contacts database program that presents the user with a menu that allows...
in java Write a contacts database program that presents the user with a menu that allows the user to select between the following options: Save a contact. Search for a contact. Print all contacts out to the screen. Quit If the user selects the first option, the user is prompted to enter a person's name and phone number which will get saved at the end of a file named contacts.txt. If the user selects the second option, the program prompts...
Write a program in Java, that creates a Jframe with a menu containing only file. Inside...
Write a program in Java, that creates a Jframe with a menu containing only file. Inside file there should be items: Open, Save, and Save As. Selecting open prompts the user to input a file name to a txt document containing employee information and displays a Jtable with the information, which can be edited. With column headers {"First Name" , "Last Name" , "Occupation" , "Office #"} Example: Gary Osbourn Teacher 113 Michelle Ramirez Teacher 101 Ava Gomez Principal 120...
java code Write a program that gives the user a menu of six choices (use integers)...
java code Write a program that gives the user a menu of six choices (use integers) to select from. The choices are circle, triangle, cone, cylinder, sphere, and quit. (The formulas are given below.) Once the figure is calculated, an informative message should be printed and the user shown the menu again, so that another choice can be made. The formulas are: Area of circle: a = 3.14 * radius * radius Area of triangle: a = ½ base *...
Write a Java program that allows the user to specify a file name on the command...
Write a Java program that allows the user to specify a file name on the command line and prints the number of characters, words, lines, average number of words per line, and average number of characters per word in that file. If the user does not specify any file name, then prompt the user for the name.
Write a program called Assignment3 (saved in a file Assignment3 .java) that asks a user to...
Write a program called Assignment3 (saved in a file Assignment3 .java) that asks a user to enter two strings. First, the program prompts: Please enter a string. The program should read in the string, and prompts: Please enter another string. The program reads in two strings and it prints a menu to the user. The program asks for user to enter an option and performs one of the following: Here are the options on the menu: Option a: checks if...
Write a JAVA program by making a LOGIN form using Excel file for validation. if user...
Write a JAVA program by making a LOGIN form using Excel file for validation. if user is found, display the user's First Name and Last Name.
Question 1: Write a Java program that prompts the user to input a file name (existing...
Question 1: Write a Java program that prompts the user to input a file name (existing text file), then calculate and display the numbers of lines in that file. Also calculate and display the length of the longest line in that file. For example, if the input file has the following lines: Hello This is the longest line Bye The output should be: The file has 3 lines. The longest line is line 2 and it has 24 characters. Test...
Write a method in JAVA that does this: Presents the user with a header stating this...
Write a method in JAVA that does this: Presents the user with a header stating this is for assignment: Lab, and the names Bob and Bill Present the user with a menu to run a random method(just make this a dummy method) , another random method method,(just make this a dummy method) or another dummy method (just make this a dummy method) Repeat the menu until the user enters -1.
Write a program names EncryptDecrypt.java that has the following menu choices: Print menu and allow user...
Write a program names EncryptDecrypt.java that has the following menu choices: Print menu and allow user to choose options. The program must have a file dialogue box for text file. Output should be based on user choices. Read in a file Print the file to the console Encrypt the file and write it to the console Write out the encrypted file to a text file Clear the data in memory Read in an encrypted file Decrypt the file Write out...
JAVA Program Write a program that prompts the user for data until the user wishes to...
JAVA Program Write a program that prompts the user for data until the user wishes to stop (you must have a while loop) (You must read in at least 8 to 10 sets of voter data using dialog boxes) The data to read in is: The registration of the voter (Democrat, Republican or other) The gender of the voter The Presidential candidate the voter is choosing (Trump or Biden) Which candidate has done better to manage the economy? (Trump or...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT