Question

In: Computer Science

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 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

///////////////////ContactsProgram.java//////////////////////////////////

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

public class ContactsProgram {
   private static final String FILE_NAME="contacts.txt";//filename is taken as a constant
  
   //scanner and FileWriter instance variable declared
   private static Scanner sc = null;
   private static FileWriter fw = null;
  
   //main method
   public static void main(String[] args){
       File file = new File(FILE_NAME);
       try {
           file.createNewFile();
       } catch (IOException e) {
           System.out.println("Error:"+e.getMessage());
       }//A new file is created in the classpath
      
       do{
           int choice = printMenu();
          
           //menu logic based on user choice
           if(choice ==1){ //if 1: save contact
               saveContact(file);
           }else if(choice ==2){ //if 2: search contact
               searchContact(file);
           }else if(choice ==3){ //if 3: display all contacts
               printAllContacts(file);
           }else if(choice ==4){//if 4: exit after closing scanner
               System.out.println("Thank you!");
               sc.close();
               break;
           }else{//other choice: show error
               System.out.println("Error: Invalid choice!");
           }
          
       }while(true);//loop indefinitely until user choose 4
      
   }
  
   /**
   * get the menu choice from user
   * @return
   */
   public static int printMenu(){
       sc = new Scanner(System.in);
       System.out.println("1. Save a contact.");
       System.out.println("2. Search for a contact.");
       System.out.println("3. Print all contacts out to the screen.");
       System.out.println("4. Quit.");
      
       System.out.println("Enter your choice:");
       int choice = Integer.parseInt(sc.nextLine());
       return choice;
   }
  
   /**
   * Take data from user and store contact in the next available line in contacts file
   * @param file
   */
   public static void saveContact(File file){
       sc = new Scanner(System.in);
       System.out.println("Enter person's name:");
       String name = sc.nextLine();
       System.out.println("Enter person's phone number:");
       String phoneNumber = sc.nextLine();
       try {
           fw = new FileWriter(file,true); //open the file in append mode to write
           fw.append(name +","+phoneNumber+"\n");//append the line
           fw.close();//close the fw
       } catch (IOException e) {
           System.out.println("Error in writing into file!");
       }
      
   }
  
   /**
   * search contact's phone number from file if the entered name is found
   * if name is not found then error message will be displayed.
   * @param file
   */
   public static void searchContact(File file){
       sc = new Scanner(System.in);
       System.out.println("Enter persons name to search:");
       String name = sc.nextLine();
       String phoneNumber = null;
       try {
           sc = new Scanner(file);
       } catch (FileNotFoundException e) {
           System.out.println("file not found!");
           return;
       }
       while(sc.hasNextLine()){
           String currentLine = sc.nextLine();
           String[] data = currentLine.split(",");
           if(data[0].equals(name)){
               phoneNumber = data[1];
               break;
           }
       }
       if(phoneNumber!=null){
           System.out.println("Phone number for "+name + " is : "+phoneNumber);
       }else{
           System.out.println("Tha name "+name+" is NOT FOUND in the contacts file!");
       }
      
   }
  
   //print all contacts form file in console
   public static void printAllContacts(File file){
       try{      
           sc = new Scanner(file);
       }catch(FileNotFoundException fe){
           System.out.println("File Not Found!");
           return;
       }
       int counter = 0;
       while(sc.hasNextLine()){
           counter++;
           if(counter ==1){
               System.out.println(String.format("%-20s\t%-20s", "Name","PhoneNumber"));
               System.out.println("----------------------------------------------------------");
           }
           String currentLine = sc.nextLine();
           String[] data = currentLine.split(",");
           String name = data[0];
           String phoneNumber = data[1];
           System.out.println(String.format("%-20s\t%-20s", name,phoneNumber));
       }
      
       if(counter==0){//if there is no entry in the file
           System.out.println("Error:There is no contacts to be displayed!");
       }
   }

}


==================================

OUTPUT

==================================

1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
1
Enter person's name:
tomas
Enter person's phone number:
5675675432
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
1
Enter person's name:
samuel
Enter person's phone number:
3344556677
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
1
Enter person's name:
ian
Enter person's phone number:
8765432100
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
1
Enter person's name:
jacky
Enter person's phone number:
6758760987
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
3
Name     PhoneNumber   
----------------------------------------------------------
tomas    5675675432
samuel     3344556677
ian    8765432100
jacky    6758760987
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
2
Enter persons name to search:
samuel
Phone number for samuel is : 3344556677
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
2
Enter persons name to search:
nil
Tha name nil is NOT FOUND in the contacts file!
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
1
Enter person's name:
nil
Enter person's phone number:
0157896321
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
3
Name     PhoneNumber   
----------------------------------------------------------
tomas    5675675432
samuel     3344556677
ian    8765432100
jacky    6758760987
nil    0157896321
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
2
Enter persons name to search:
nil
Phone number for nil is : 0157896321
1. Save a contact.
2. Search for a contact.
3. Print all contacts out to the screen.
4. Quit.
Enter your choice:
4
Thank you!

======================================

The file: contacts.txt(that has been generated

======================================


Related Solutions

Please write the code JAVA Write a program that allows the user to enter the last...
Please write the code JAVA Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The program should then output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election. A sample output is: Candidate      Votes Received                                % of Total Votes...
Java Programming: Write a program that allows the user to compute the power of a number...
Java Programming: Write a program that allows the user to compute the power of a number or the product of two numbers. Your program should prompt the user for the following information: • Type of operation to perform • Two numbers (the arguments) for the operation to perform The program then outputs the following information: • The result of the mathematical operation selected. Menu to be displayed for the user: MATH TOOL 1. Compute the power of a number 2....
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.
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 *...
In Java: Write a program called F2C that allows the user to convert from degrees Fahrenheit...
In Java: Write a program called F2C that allows the user to convert from degrees Fahrenheit to degrees Celsius. The program should prompt for a temperature in Fahrenheit and output a temperature in Celsius. All calculations should be done in in ints, so be careful of truncation.
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.
Java program Statement: Provide a user interface to the invoice program in Section 12.3 that allows...
Java program Statement: Provide a user interface to the invoice program in Section 12.3 that allows a user to enter and print an arbitrary invoice. Do not modify any of the existing classes. ..... ..... ..... /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product...
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...
Write a GUI that allows the user to do the following: Create a new Patient Database...
Write a GUI that allows the user to do the following: Create a new Patient Database if it doesn’t exist yet by the click of a button. Create a second button that populates the database with the appropriate Asset table if it does not exist yet, and fill the table with at least 10 patients. Connect to the Patient Database and display all current patients in a List by default. You will have to create a Patient Class. This class...
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