A Java question. Here is a text file containing the information about the salari
ID: 3824326 • Letter: A
Question
A Java question. Here is a text file containing the information about the salaries of the top 10 highest paid CEOs.
-------------------------------------------------------------------------------------------------------------------------
Write a program CEOSalaries to print a list which contains the ticker symbol, colon space, the name of the CEO, space, and the salary printed with a $ and comma separators. Use printf. The first record looks like this:
After all the records are printed, print: "Average salary: " and then the average salary with a $ and comma separators and 2 decimal places.
Note: You need to remove the $ and commas before using Integer.parseInt to convert a strings to an int.
The file name will be provided in the command line arguments.
Catch the exception if the file does not exist and print this message: No such file: filename
To process data in a file, you have to test the file to determine the format of the data. In this case, the name of the CEO can be either two or three words. Company names also varies in length. If the CEO name has three parts, one will be an initial, (like J. in the first entry). The initial may be either the first or the second name. Notice that the last name is the third name from the end.
Explanation / Answer
import java.util.*;
import java.io.*;
public class SalaryPayroll
{
public static void main(String[] args) throws FileNotFoundException
{
String name, ticker, tmp, sal, line, filename;
String[] arr;
long sum=0;
long avg;
int i=0;
instructions();
filename=args[0];
Scanner sc=new Scanner(new File(filename));
line = sc.nextLine();
while(sc.hasNextLine()){
line = sc.nextLine(); // read line
i++; // increment the record count
arr=line.split("\t"); // split each record based on tab
ticker=arr[0]; // extract records
name=arr[2];
tmp=arr[4];
sal=tmp;
tmp=tmp.substring(1); // rempve $ sign
tmp=tmp.replaceAll(",",""); // remove commas
sum+= Long.parseLong(tmp);
System.out.println(ticker+": "+name+" "+sal);
}
avg = sum/i;
System.out.println("Average Salary is $"+avg);
}
public static void instructions()
{
System.out.println(" Instructions This program reads a txt file which has tab saperated info e:g ticker and Company name are saoerated by tab and CEO name and year are saperated by tab and so on ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.