Here is the problem: 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 program that reads such a file and displays the total amount for each service category. Display an error if the file does not exist of the format is incorrect.
Here is what I have:
package practice; import java.io.*; import java.io.FileNotFoundException; import java.util.*; import java.io.PrintWriter; public class practice1 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.println("Please enter input file name: "); String inputFileName = console.next(); System.out.println("Please enter desired output file name: "); String outputFileName = console.next(); console.useDelimiter(";"); //Construct Scanner and PrintWriter objects for reading and writing File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = new PrintWriter(outputFileName); double dinnerTotal = 0; double conferenceTotal = 0; double lodgingTotal = 0; double total = dinnerTotal + conferenceTotal + lodgingTotal; //Read the input and write the output while (in.hasNext()) { String line = in.nextLine(); String[] parts = line.split(";"); if(parts[2].equals("Conference")){ conferenceTotal = conferenceTotal+ Double.parseDouble(parts[3]); } else if(parts[2].equals("Dinner")){ dinnerTotal += Double.parseDouble(parts[3]); } else if(parts[2].equals("Lodging")){ lodgingTotal += Double.parseDouble(parts[3]); } } out.printf("Dinner Total:", dinnerTotal); out.println(); out.printf("Conference Total:", conferenceTotal); out.println(); out.printf("Lodging Total", lodgingTotal); out.println(); out.printf("Total", total); in.close(); out.close(); } }
This program creates a new file that looks like this: Dinner Total Conference Total Lodging Total Total
It doesn’t print the actual totals though. How do I print the totals?
Answer
double total = dinnerTotal + conferenceTotal + lodgingTotal;
line needs to go below the while
loop.