Source of TransactionReader.java


  1: //TransactionReader.java

  3: import java.io.FileNotFoundException;
  4: import java.io.File;
  5: import java.util.Scanner;

  7: public class TransactionReader
  8: {
  9:     public static void main(String[] args)
 10:     {
 11:         String fileName = "Transactions.txt";
 12:         try
 13:         {
 14:             Scanner inputStream = new Scanner(new File(fileName));
 15:             String line = inputStream.nextLine(); //Read header line
 16:             double totalSales = 0;
 17:             System.out.println();
 18:             //Read the rest of the file, line by line
 19:             while (inputStream.hasNextLine())
 20:             {
 21:                                 line = inputStream.nextLine();
 22:                                 //Extract SKU(Stock Keeping Unit),quantity,price,description
 23:                                 String[] items = line.split(",");
 24:                                 String SKU = items[0];
 25:                                 int quantity = Integer.parseInt(items[1]);
 26:                                 double price = Double.parseDouble(items[2]);
 27:                                 String description = items[3];
 28:                                 System.out.printf("Sold %d of %s (SKU: %s) at $%1.2f each.\n",
 29:                                         quantity, description, SKU, price);
 30:                                 totalSales += quantity * price;
 31:                         }
 32:                         System.out.printf("Total sales: $%1.2f\n", totalSales);
 33:             inputStream.close( );
 34:         }
 35:         catch(FileNotFoundException e)
 36:         {
 37:             System.out.println("Error opening the file " + fileName + ".");
 38:         }
 39:     }
 40: }