A hotel salesperson enters sales in a text file. Each line contains the followin
ID: 3683452 • Letter: A
Question
A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Write a java program that reads such a file and displays the total amount for each service category. Display an error if the file does not exist or the format is incorrect. Make sure the program can read a text file and that writes a separate file for each service category, containing the entries for that category. Name the output files Dinner.txt, Conference.txt, and so on.
Explanation / Answer
Java code:
//Header file section
import java.util.Scanner;
import java.io.*;
//main class
public class SalesTestDemo
{
//main method
public static void main(String[] args) throws IOException
{
String inFile;
String line;
double total = 0;
Scanner scn = new Scanner(System.in);
//Read input file name
System.out.print("Enter input file Name: ");
inFile = scn.nextLine();
FileReader fr = new FileReader(new File(inFile));
BufferedReader br = new BufferedReader(fr);
System.out.println("Name Service_Sold Amount Event Date");
System.out.println("=====================================================");
line = br.readLine();
//Each line contains the following, separated by semicolons:
//The name of the client, the service sold
//(such as Dinner, Conference, Lodging, and so on)
while(line != null)
{
String temp[] = line.split(";");
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]+" ");
if(i == 1)
System.out.print(" ");
}
//Calculate total amount for each service category
total += Double.parseDouble(temp[2]);
System.out.println();
line = br.readLine();
}
//Display total amount
System.out.println(" Total amount for each service category: "+total);
}
}
inputSale.txt:
Peter;Dinner;1500;30/03/2016
Bill;Conference;100.00;29/03/2016
Scott;Lodging;1200;29/03/2016
Output:
Enter input file Name: inputSale.txt
Name Service_Sold Amount Event Date
=====================================================
Peter Dinner 1500 30/03/2016
Bill Conference 100.00 29/03/2016
Scott Lodging 1200 29/03/2016
Total amount for each service category: 2800.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.