Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 1 This is a Java project The names.txt file contains one name per line.

ID: 3690005 • Letter: P

Question

Problem 1

This is a Java project

The names.txt file contains one name per line. There are duplicate names in the file. We want to generate an invitation list but don’t want to send multiple invitations to the same person.

Write a method that eliminates the duplicate names by using a HashSet. Read each name from the file, echo it to the console, add it to the HashSet, and then output all names in the HashSet to generate the invitation list without duplicates.

Hint: You can use following code to open a file

Scanner inputStream = new Scanner(new FileInputStream("names.txt"));

You do not need to handle file open errors - for this assignment it is ok to assume the file exists and is accessible to your program. It is not necessary to validate the input for this problem.

Note: You must access the names.txt file in the default location (typically the project root folder). You are not allowed to include a path to the file. Failure to follow this rule will result in a 25% deduction.

Explanation / Answer

import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
* @author Srinivas Palli
*
*/
public class SendInvitations {

   public static void main(String[] args) {

       try {
           Scanner inputStream = new Scanner(new FileInputStream("names.txt"));
           Set<String> set = removeDuplicates(inputStream);
           sendInvitations(set);
          
       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       }
   }

   /**
   * method to remove duplicates
   *
   * @param inputStream
   * @return
   */
   public static Set<String> removeDuplicates(Scanner inputStream) {

       Set<String> set = new HashSet<String>();
       while (inputStream.hasNext()) {
           String line = inputStream.nextLine();
           System.out.println(line);

           set.add(line);
       }

       return set;
   }

   /**
   * method to send invitation
   *
   * @param set
   */
   public static void sendInvitations(Set<String> set) {

       Iterator<String> it = set.iterator();
       while (it.hasNext()) {
           System.out.println("Send invitation to " + it.next());

       }
   }

}

names.txt

srinivas
rajesh
pavan
kishore
rajesh
anil
srinu
ravi

OUTPUT:

srinivas
rajesh
pavan
kishore
rajesh
anil
srinu
ravi
Send invitation to anil
Send invitation to kishore
Send invitation to rajesh
Send invitation to pavan
Send invitation to srinu
Send invitation to srinivas
Send invitation to ravi

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote