Question
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

FirstName Radioactive Man LastName DateOfBirth SSN Salary Role Zip Phone garlic 9/29/1912 846330158 Administration 69989 3915

These are the coding instructions. Questions 1,2 and 3

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

1eimport java.io.File: 2 import java.io. FileNot FoundException; 3 import java.util.scanner American He STC 4 (defaulti 5 > A
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 7752750033 lemon 704192984 Administration 38259 39157 3917814119 Chief broccoli 4/16/1964 221616019 Front Office 79981 39157 8190073149 Clayface 3/27/2011 218594031 Administration carrot 42882 39157 4391168610 Anole cherry 5/8/1946 812410312 Administration 89208 39157 9134971042 Metamorpho Aztek cabbage 4/28/1968 9/25/1987 758339161 Back Office 32633 39157 3341671152 book 688616471 Back Office 83848 39157 8586089659 Black Spider Captain Canada sSolomon Grundy calculator 8/19/1955 514638108 Back Office 60781 39157 6224072023 4/27/1900 4/20/1997 pomegranate 348804383 Back Office 67225 39157 6883874410 candle 307431255 Back Office 21080 39157 2158660083 Mr. Miracle lemon 3/7/2008 722299722 Administration 30442 39157 3117283474 Bumblebee kiwi 3/21/2001 275341494 Back Office 63293 39157 6481263373 Aquaman Geo-Force Doctor Druid peach 4/4/1942 262465566 Back Office 96360 39157 9867353847 headphones 11/11/1952 335096045 Back Office 84953 39157 8699281194 8/16/1923 10/5/1921 357678855 Back Office 19067 39157 1952511287 carrot Doctor Mist pencil landrover 224076302 Back Office 17934 39157 1836460008 Crimson Avenger 6/22/1937 761946418 Back Office 91790 39157 9399350958 Dove 11/19/1985 286820377 Back Office 18212 39157 1864933929 tv Bulletman Radioactive Man headphones 6/16/1942 11/21/1917 408855949 Back Office 39157 4566651901 44596 788178640 Back Office bucket 19152 39157 1961261322 696411134 Back Office Air Wave fiat 6/6/1952 29882 39157 3059927923 Captain Marvel Damage strawberry 10/12/1993 10/20/1989 472548670 Back Office 41825 39157 4282939794 eggplant 345132584 Administration 27049 39157 2769846097 onion Alchemist 2/15/1922 4/19/2015 37165 39157 3805761300 333124581 Front Office 375174368 Back Office Empress Firehawk bulb 46453 39157 4756860570 39157 3929292623 10/5/1969 693878414 Back Office 38371 eggplant
Question 1 Review the attached CSV data file. You are going to need to parse this file into the application you write. Objective: The deliverable for this first question is to write a program that imports the contents of the CSV into memory so that various calculations and operations can be performed on it. You will be taking the following types of actions on this data after it is imported: Return the top X number of records Grouping Sorting Filtering etc. You may use any method you choose to manipulate the data, array list, database, etc. The programming languages used and the way you solve the problem is completely up to you. We would if you prefer if you use a Microsoft .NET language to develop this, but it's totally acceptable if you'd like to use another language Be prepared to explain your reasoning for your approach and implementation of the solution to this assignment. Important notes relating to this assignment The first row contains the field definition Columns are separated by comma a. b. Question 2 Using the data imported from the file, write a function or method to calculate and print the average salary for each role. Question 3 Using the data imported from the file, write a function or method to calculate and print the average salary by zip code for all zip codes that start with the characters 35 (example: 35425).
1eimport java.io.File: 2 import java.io. FileNot FoundException; 3 import java.util.scanner American He STC 4 (defaulti 5 > Ame 6 >a JRE System 7 public class American Health Tech Assessment ( data.csv 8 public static void main (String [] args) /TODO Auto-generated method stub /.csv comma seperated values 9e Basic Mindstc 10 BumperCar 11 CSCI361 Mini 12 CSCI361 Proj 13 CSCI361Assig String fileName "data.csv" File file = new File (fileName);//TODO: read about File 14 DrivingFowar 15 Homework 0 16 try Scanner inputStream = new Scanner (file); while (inputstream.hasNext ()) { String data //Each line will end in three stars System. out.println (data+ ) 17 PingServer 18 RandomDrivi 19 inputStream.next () RC Car 20 21 Sudoku Solve Rov3r 22 23 24 25 TestMotor TestUltra Touch inputStream.close (); ) catch (FileNotFoundException e) / TODO Auto-generated catch block e.printstackTrace () Ultrasonic Dis 26 27 28 29 30 I . d Problems Javadoc Declaration Console American Health Tech Assessment [Java Application) CAProgram FilesJavaljre18.0.131\binjavaw.exe (Jun 24, 2 Helen, Birch, 6/2/2017,904385092, Medical** Records, 22907,56788, 2345678889*** Adam, BoonHoon, 12/12/1912, 426657986, Back*x office,15640,39202,1601555123** John, Smith, 1/1/1955, 425121233,Medical*** Records, 54253, NULL, 5555551234**
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Record.java

public class Record {
private String firstName, lastName, dateOfBirth, SSN, role;
private double salary;
private String zip, phone;

public Record(String firstName, String lastName, String dateOfBirth, String SSN, String role,
double salary, String zip, String phone)
{
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.SSN = SSN;
this.role = role;
this.salary = salary;
this.zip = zip;
this.phone = phone;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

public String getDateOfBirth() {
return dateOfBirth;
}

public String getSSN() {
return SSN;
}

public String getRole() {
return role;
}

public double getSalary() {
return salary;
}

public String getZip() {
return zip;
}

public String getPhone() {
return phone;
}
}

American_Health_Tech_Assessment.java (Main class)

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

public class American_Health_Tech_Assessment {
  
private static final String FILENAME = "data.csv";
public static void main(String[]args)
{
File file = new File(FILENAME);
ArrayList<Record> records = new ArrayList<>();
Scanner fileReader;
try
{
fileReader = new Scanner(file);
fileReader.nextLine(); // ignore the first line(column header) in the file
while(fileReader.hasNextLine())
{
String[] data = fileReader.nextLine().split(",");
String firstName = data[0];
String lastName = data[1];
String dob = data[2];
String ssn = data[3];
String role = data[4];
double salary = Double.parseDouble(data[5]);
String zip = data[6];
String phone = data[7];
  
Record record = new Record(firstName, lastName, dob, ssn, role, salary, zip, phone);
records.add(record);
}
fileReader.close();
  
// get all the roles(unique) from the records
ArrayList<String> roles = new ArrayList<>();
for(Record rec : records)
{
if(!roles.contains(rec.getRole()))
roles.add(rec.getRole());
}
  
// now display the average salary for all the roles
System.out.println("*** AVERAGE SALARY FOR ALL ROLES ***\n------------------------------------");
for(String role : roles)
{
calculateAverageSalaryBasedOnRole(role, records);
}
  
// calculate average salary based on parts of a given zip
String userAskedZip = "35";
System.out.println("*** AVERAGE SALARY FOR ALL ZIP STARTING WITH " + userAskedZip
+ " ***\n---------------------------------------------------");
calculateAverageSalaryBasedOnZip(userAskedZip, records);
  
}catch(FileNotFoundException fnfe){
System.out.println("File not found: " + FILENAME);
}
}
  
public static void calculateAverageSalaryBasedOnRole(String role, ArrayList<Record> records)
{
double totalSalary = 0;
int count = 0;
for(Record rec : records)
{
if(rec.getRole().equals(role))
{
totalSalary += rec.getSalary();
count++;
}
}
double average = (totalSalary / count);
System.out.println("Number of records having " + role + " as role is = " + count
+ "\nTheir average salary is = $" + String.format("%.2f", average) + "\n");
}
  
public static void calculateAverageSalaryBasedOnZip(String zip, ArrayList<Record> records)
{
double totalSalary = 0;
int count = 0;
  
for(Record rec : records)
{
if(rec.getZip().substring(0, 2).equals(zip))
{
totalSalary += rec.getSalary();
count++;
}
}
double average = (totalSalary / count);
System.out.println("Number of records having zip starting with " + zip + " is = " + count
+ "\nTheir average salary is = $" + String.format("%.2f", average) + "\n");
}
}

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

CD run: AVERAGE SALARY FOR ALL ROLES Number of records having Administration as role is= 5 Their average salary is $50844.40

Add a comment
Know the answer?
Add Answer to:
Reading and parsing a CSV file in Java NOTE: a.) The first row contains the field...
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 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...

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

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

  • Sample of CSV file tweet tweet_id airline_sentiment airline 567591480085463000 negative United 567588278875213000 neutral Delta 567590027375702000 negative...

    Sample of CSV file tweet tweet_id airline_sentiment airline 567591480085463000 negative United 567588278875213000 neutral Delta 567590027375702000 negative Delta 5 567592368451248000 negative United 6 567594449874587000 negative Southwest United United United @united yes. We waited in line for almost an hour to do so. Some passengers just left not wanting to wait past 1am. @JetBlue's new CEO seeks the right balance to please passengers and Wall ... - Greenfield Daily Reporter http://t.co/LM3opxkxch @JetBlue is REALLY getting on my nerves !! YOY#nothappy @united the...

  • The file containing the JAVA files, pseudocode file and doc file that have written for this...

    The file containing the JAVA files, pseudocode file and doc file that have written for this lab. Preamble The file releasedates.txt contains a list of video games and their release dates. Each line of the file contains the release date, a tab character, and then the name. The list is currently totally unsorted. The object of today's lab is to write a series of methods that allow us to perform the following tasks: read contents from a file and store...

  • 1.b) Create a Java application Lab3Part1b. Make sure you create a NEW project with the specific...

    1.b) Create a Java application Lab3Part1b. Make sure you create a NEW project with the specific name just given. You need to make sure the projects you create and submit have the correct names and the name of the file and name of the class are the same. The names are case sensitive. In this new project, set up your program to read in the data from the file SciFiDataBMTClean.txt using a Scanner. {file/Scanner setup 2 points}   Declare the variables...

  • Q2. Retrieve the names of all employees from the employee table to produce output on CSV...

    Q2. Retrieve the names of all employees from the employee table to produce output on CSV format or delimited format with a common delimeter, rather than separete columns. Hint:Put the whole row into a string with a semicolon as the seperator(delimeter) between thecolumns: FORMAT:(fname;minit;lname) Example: EMPLOYEES -------------- James;E;Borg Frank;T;Wong Q3. Write a query to show the employees name from the employee table in this format: first letter of the first name, followed by a dot, a blank, and the full...

  • Excel file Homework1 - invoices.xlsx contains data about invoices of a reseller of office equipment that...

    Excel file Homework1 - invoices.xlsx contains data about invoices of a reseller of office equipment that ships its products to customers in several countries. The tables in the workbook refer to data collected from different systems within the company. a) Copy worksheet “InvoiceHeader” into a new worksheet. For each invoice in the new worksheet, show the matching information from the other tables: Invoice date, Invoice Number, Customer ID, Customer Name, Country, Invoice Quantity, Unit Cost, Unit Price. b) In the...

  • Tasks A. (20 po ints) In Lab 6, you defined and implemented a class called Date....

    Tasks A. (20 po ints) In Lab 6, you defined and implemented a class called Date. You will make some modific ation to the Date class so that it mccts the folowing specific ations: The Date class consists of three private member variables: Member Variable year month day Description An int variable that hokls the value of a year. An int variable that hokds the value of a month An int variable that hokis the value of a day. 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
ADVERTISEMENT