Source of TransactionReader.java


  1: //TransactionReader.java

  3: import java.io.FileInputStream;
  4: import java.io.FileNotFoundException;
  5: import java.io.IOException;
  6: import java.io.File;
  7: import java.util.Scanner;

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