Question

Problem 2. Write a program that reads in the file names.txt from data\ on the flashdrive...

Problem 2. Write a program that reads in the file names.txt from
data\ on the flashdrive and counts all of the unique first names
in the file. Find the name that occurs the most.
a. Note: you will want to import the filename as args[0] to avoid hardcoding the filename.
If you have the exact number of elements in your array as your data (read it in a method) returning the Array.
then you can use Arrays.sort(myArray) to sort the array. You will need to import java.util.
Once it is sorted, this problem is trivial.
Arrays.sort(myArray,0,size)
call this one ....UniqueNames
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:-

The below is the required source code for the given problem in Java

Code:-

public class FirstNAmes {
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(new File(args[0]));
        HashMap<String, Integer> map = new HashMap<>();
        String name = "";

        while(sc.hasNextLine()){
            name = sc.nextLine().split(" ")[0];
            if(map.containsKey(name)){
                map.put(name, map.get(name)+1);
            }
            else{
                map.put(name,1);
            }
        }

        int max = 0;
        String names[] = new String[map.size()];
        int i=0;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            names[i] = entry.getKey();
            i++;
            if (map.get(entry.getKey()) > max) {
                max = map.get(entry.getKey());
            }
        }

        for(Map.Entry<String, Integer> entry : map.entrySet()){
            if (map.get(entry.getKey()) == max) {
                System.out.println("Most frequent first name: "+entry.getKey());
                break;
            }
        }

        Arrays.sort(names, 0, map.size());
        for(int j=0; j<names.length; j++){
            System.out.println(names[j]);
        }

        sc.close();
    }
}

If you find difficulty to understand the code, please let me know in comments tab below, Then I will provide another code or else i will any modifications in the present code. Hope it will helps you. Please give Thumbs Up!! Thank you for posting the question, All the best.

Add a comment
Know the answer?
Add Answer to:
Problem 2. Write a program that reads in the file names.txt from data\ on the flashdrive...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA Code: Complete the program that reads from a text file and counts the occurrence of...

    JAVA Code: Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code already opens a specified text file and reads in the text one line at a time to a temporary String. Your task is to go through that String and count the occurrence of the letters and then print out the final tally of each letter (i.e., how many 'a's?, how many 'b's?, etc.) You can...

  • The name of the C++ file must be search.cpp Write a program that will read data...

    The name of the C++ file must be search.cpp Write a program that will read data from a file. The program will allow the user to specify the filename. Use a loop that will check if the file is opened correctly, otherwise display an error message and allow the user to re-enter a filename until successful. Read the values from the file and store into an integer array. The program should then prompt the user for an integer which will...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I have a program that reads a file and then creates objects from the contents of...

    I have a program that reads a file and then creates objects from the contents of the file. How can I create a linked list of objects and use it with the package class instead of creating and using an array of objects? I am not allowed to use any arrays of objects or any java.util. lists in this program. Runner class: import java.util.Scanner; import java.io.*; class Runner { public static Package[] readFile() { try { File f = new...

  • .Using OOP, write a C++ program that will read in a file of names. The file...

    .Using OOP, write a C++ program that will read in a file of names. The file is called Names.txt and should be located in the current directory of your program. Read in and store the names into an array of 30 names. Sort the array using the selection sort or the bubblesort code found in your textbook. List the roster of students in ascending alphabetical order. Projects using global variables or not using a class and object will result in...

  • Java. (20 pts)          Write a program that reads all the numbers from the file mynums.dat...

    Java. (20 pts)          Write a program that reads all the numbers from the file mynums.dat and prints out the sum of the positive values from the file. Assume that the file contains only numeric values. You must output an error if the file can't be opened. You must write the complete program and the output when the program runs successfully must conform exactly to the sample output. Bonus ( 5 pts). Output an error if the file contains non-numeric...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Write a C++ code to make a simple program that imports the input file in and...

    Write a C++ code to make a simple program that imports the input file in and gets the results as specified Please follow the instructions and paste the code below as the answer with a screenshot of the output to prove it worked. Input file -> https://www.dropbox.com/s/444jofkchu6ylwr/names.txt?dl=0 Scoring Names You will be using the provided names.txt file, text file containing over five-thousand first names, and you will calculate a score for each name. Begin by reading the names from the...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • IN MIPS PLEASE. Need help writing a MIPS program that reads from a text file named...

    IN MIPS PLEASE. Need help writing a MIPS program that reads from a text file named "input.txt" and places it in a buffer. A buffer of 80 bytes is more than enough. Before you call your function, set $a0 equal to the address of the filename and $a1 to the address of the buffer where data is stored. The function should return the number of bytes read in $v0. In the main program, print an error message and terminate the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT