Question
Reading and parsing a CSV data file in java

Note:
I.) the first row contains the field definition
II.) Columns are separated by comma

This is the data.csv file
A D F G H J K 1 FirstName LastName DateOfBirth SSN Role Salary Zip Phone 2 Radioactive Man BMockingbird 4Captain Triumph 5 De

These are the instructions
Question 1 Review the attached CSV data file. You are going to need to parse this file into the application you write. Object

This is my code so far
image.png
0 0
Add a comment Improve this question Transcribed image text
Answer #1
//American_Health_Tech_Assesment.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;

public class American_Health_Tech_Assesment {
    public static void main(String[] args) {
        String fileName = "data.csv";
        File file = new File(fileName);
        // array list for storing individuals records
        ArrayList<String> firstName = new ArrayList<>();
        ArrayList<String> lastName = new ArrayList<>();
        ArrayList<String> dateOfBirth = new ArrayList<>();
        ArrayList<String> ssn = new ArrayList<>();
        ArrayList<String> role = new ArrayList<>();
        ArrayList<Float> salary = new ArrayList<>();
        ArrayList<String> zip = new ArrayList<>();
        ArrayList<String> phone = new ArrayList<>();
        Scanner inputStream = null;
        boolean isException = false;
        try {
            inputStream = new Scanner(file);
            inputStream.nextLine(); // skipping headers
            while (inputStream.hasNextLine()) {
                // splitting line by ,
                String words[] = inputStream.nextLine().trim().split(",");
                if (words.length >= 8) {
                    firstName.add(words[0].trim());
                    lastName.add(words[1].trim());
                    dateOfBirth.add(words[2].trim());
                    ssn.add(words[3].trim());
                    role.add(words[4].trim());
                    salary.add(Float.valueOf(words[5].trim()));
                    zip.add(words[6].trim());
                    phone.add(words[7].trim());
                }
            }

        } catch (
                FileNotFoundException e) {
            isException = true;
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        if(!isException){
            // calling function
            printAvgSalaryForEachRole(role, salary);
            System.out.println();
            printAvgSalaryByZipCode(zip, salary, "35");
        }

    }

    public static void printAvgSalaryForEachRole(ArrayList<String> role, ArrayList<Float> salary) {
        int count;
        // map for storing role and sum of salary
        HashMap<String, Float> roleSalaryMap = new HashMap<>();
        for (int i = 0; i < role.size(); i++) {
            String curRole = role.get(i);
            float curSal = salary.get(i);
            // if role already added in map 
            // updating sum of salary
            if (roleSalaryMap.containsKey(curRole)) {
                float t = roleSalaryMap.get(curRole);
                roleSalaryMap.put(curRole, t + curSal);
            } else {
                // adding initial entry for role and salary
                roleSalaryMap.put(curRole, curSal);
            }

        }
        System.out.printf("%-20s%10s\n", "Role", "Average Salary");
        System.out.println("-------------------------------------\n");
        for (String name : roleSalaryMap.keySet()) {
            count = Collections.frequency(role, name);
            float curAvgSal = roleSalaryMap.get(name) / count;
            System.out.printf("%-20s%10.2f\n", name, curAvgSal);
        }

    }

    public static void printAvgSalaryByZipCode(ArrayList<String> zip, ArrayList<Float> salary, String zipStartWith){
        int count;
        HashMap<String, Float> zipSalaryMap = new HashMap<>();
        for (int i = 0; i < zip.size(); i++) {
            String curZip = zip.get(i);
            float curSal = salary.get(i);
            // if zip starts with given then only processing entry
            if(curZip.startsWith(zipStartWith)) {
                if (zipSalaryMap.containsKey(curZip)) {
                    float t = zipSalaryMap.get(curZip);
                    zipSalaryMap.put(curZip, t + curSal);
                } else {
                    zipSalaryMap.put(curZip, curSal);
                }
            }

        }

        System.out.printf("%-20s%10s\n", "Zip", "Average Salary");
        System.out.println("-------------------------------------\n");
        for (String name : zipSalaryMap.keySet()) {
            count = Collections.frequency(zip, name);
            float curAvgSal = zipSalaryMap.get(name) / count;
            System.out.printf("%-20s%10.2f\n", name, curAvgSal);
        }
    }
}

// Had tested with records here is the output

Average Salary Role Administration 38936.50 Zip Average Salary 35157 35936.50

Please do let me know if u have any concern..

Add a comment
Know the answer?
Add Answer to:
Reading and parsing a CSV data file in java Note: I.) the first row contains the...
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
  • Reading and parsing a CSV data file in java Note: I.) the first row contains the...

    Reading and parsing a CSV data file in java Note: I.) the first row contains the field definition II.) Columns are separated by comma This is the data.csv file These are the instructions This is my code so far A D F G H J K 1 FirstName LastName DateOfBirth SSN Role Salary Zip Phone 2 Radioactive Man BMockingbird 4Captain Triumph 5 Deathstroke, th Chief garlic 9/29/1912 846330158 Administration 39157 7166875260 69989 persimmon 9/22/1956 835340509 Administration 13884 39157 1421813391 usb...

  • Reading and parsing a CSV file in Java NOTE: a.) The first row contains the field...

    Reading and parsing a CSV file in Java NOTE: a.) The first row contains the field definition b.) Columns are separated by comma This is the data.csv file These are the coding instructions. Questions 1,2 and 3 This is my code so far FirstName Radioactive Man LastName DateOfBirth SSN Salary Role Zip Phone garlic 9/29/1912 846330158 Administration 69989 39157 7166875260 Mockingbird Captain Triumph Deathstroke, th persimmon 9/22/1956 835340509 Administration 13884 39157 1421813391 usb 7/19/1940 8/8/1970 979204716 Back Office 75710 39157...

  • Write an open_file() and a function that reads a csv data file and returns a dictionary...

    Write an open_file() and a function that reads a csv data file and returns a dictionary Microsoft Word - project09_final_RJE.docx 1/17 This project focuses on analyzing a publicly available dataset containing information about the spread of nCoV. Since this is an active situation, this dataset is constantly being updated with the latest figures. However, for our purposes, we will use a static version of the dataset provided to you with this project (ncov.csv). This static version was lasted updated on...

  • Write a C++ program that will input data from a Comma-separated values (.csv) file and output...

    Write a C++ program that will input data from a Comma-separated values (.csv) file and output some information about it. This program uses a csv file from Yahoo Finance (.csv) filename : SBUX.csv 1. Output the name of the ticker to the console screen (without the “.csv”) 2. Output the start date and end date that was found in the file 3. Output how many trading day(s) existed in the file 4. Prompt the use to input a number of...

  • I need to insert the data from a csv file which is look something like this...

    I need to insert the data from a csv file which is look something like this . into the SQL table which that I've already created . How can i do it? listing_id date available price 0 241032 1 85 1 241032 1 85 2 241032 0 3 241032 0 4 241032 0 5 241032 0 241032 0 7 241032 0 8 241032 0 9 241032 1 85 10 241032 1 85 241032 11 0 12 241032 0 13 241032...

  • Write a program that will accept from the user a text file containing hurricane data along...

    Write a program that will accept from the user a text file containing hurricane data along with an output filename. The data consists of the year, the number of storms, the number of hurricanes, and the damage in millions of US Dollars. The first line contains the word “Years” followed by the first year listed and the last year listed separated by tabs. The following lines contain the data separated by tabs. A sample text file is available in this...

  • Question 2 If you read in a csv file using read.csv() function into R, what is the resulting datastructure in which R st...

    Question 2 If you read in a csv file using read.csv() function into R, what is the resulting datastructure in which R stores the read-in data? A. numeric B. matrix    C. data.frame    D. vector    Question 3 Suppose you have 4 integers, 4 characters, and 4 logical values. Which datastructure can you use to store all 12 values? Choose one or more options. A. a vector B. a matrix C. a list D. a data frame Question 4 Suppose you have...

  • blockpy python review 16 processing json files second pic is the report.json file data BlockPy: Review 16) Process JSON The given file contains JSON data. Use the data associated with the "Employ...

    blockpy python review 16 processing json files second pic is the report.json file data BlockPy: Review 16) Process JSON The given file contains JSON data. Use the data associated with the "Employees" key (a list inside of a dictionary inside of a dictionary inside of a dictionary) to plot the distribution of employees. Note: You cannot embed the contents of the file directly in your program. Use the appropriate file handling style to access the data in the file. Note:...

  • Write a C++ program that will input data from a Comma-separated values (.csv) file and output som...

    Write a C++ program that will input data from a Comma-separated values (.csv) file and output some information about it. This program uses a csv file from Yahoo Finance (.csv) filename : SBUX.csv 1. Output the name of the ticker to the console screen (without the “.csv”) 2. Output the start date and end date that was found in the file 3. Output how many trading day(s) existed in the file 4. Prompt the use to input a number of...

  • 1. Create a file that contains 3 rows of data of the form: First Name Middle...

    1. Create a file that contains 3 rows of data of the form: First Name Middle Name Last Name Month Day Year Month Day Year GPA. This file represents student data consisting of first name, middle name, last name, registration month, registration day, registration year, birth month, birth day, birth year, current gpa. ...or you may download the data file inPut.txt. inPut.txt reads:​​​​​​​ Tsia Brian Smith 9 1 2013 2 27 1994 4.0 Harper Willis Smith 9 2 2013 9...

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
ADVERTISEMENT