// Chapter 5 Exception Handlers // page 70 and 71 Read and Write Streams // page 43 try catch finally block // inner Class // write to a csv file import java.io.FileWriter; // page 70 import java.io.IOException; // file is not found or other file issues cpt 5 import java.io.PrintWriter; // page 71 import java.util.Scanner; // ask the user to input quantity public class Orders { public static void main(String[] args) { try { // Front end order system for the user Scanner scanner = new Scanner(System.in); System.out.println("Enter the quantity of products to order: "); int quantity = scanner.nextInt(); // validation or exceptions // Product to add to cart String sku = "sku0001"; // sku0001 double price = 52.52; // Tax Rate for addToCart double taxRate = 0.07; // 7% // subTotal of Order double subTotal = quantity * price; // pass the subTotal and the taxRate to the addToCart() // addToCart will do the calculations AddToCart addToCart = new AddToCart(sku, subTotal, taxRate); addToCart.calculateTotal(); // local var NOT Class name System.out.println("Sku: " + addToCart.getSku()); System.out.println("Price: " + price); System.out.println("Quantity: " + quantity); System.out.println("Subtotal: " + addToCart.getSubTotal()); System.out.println("Tax Amount: " + addToCart.getTax()); System.out.println("Cart Total: " + addToCart.getTotal()); // Write the order to our orders.csv String fileName = "orders.csv"; // "c:/dir/subdir/file.csv" PrintWriter printWriter = new PrintWriter(new FileWriter(fileName, true)); // string to write to the csv file printWriter.println(addToCart.getSubTotal() + "," + addToCart.getTax() + "," + addToCart.getTotal()); printWriter.close(); System.out.println("Order added to " + fileName); // close any open streams in try scanner.close(); } // try // detailed errors first catch (NullPointerException err) { System.err.println("Bad data entered."); } catch (IOException err) { System.err.println("Error when writing to file: " + err.getMessage()); // user or system specific operations on the error } // last catch a general catch all catch (Exception err) { System.err.println("General Exception Error Thrown: " + err.getMessage()); } finally { // close all open streams, database connection, query or other cleanup actions in application } } // main() } // Main Class class AddToCart { private String sku; private double subTotal; private double taxRate; private double tax; private double total; public AddToCart(String sku, double subTotal, double taxRate) { this.sku = sku; this.subTotal = subTotal; this.taxRate = taxRate; } // AddToCart() public void calculateTotal() { tax = subTotal * taxRate; // amount of tax total = subTotal + tax; // add the subtotal and the tax amount } // getters public String getSku() { return sku; } public double getSubTotal() { return subTotal; } public double getTax() { return tax; } public double getTotal() { return total; } } // AddToCart Class