Assignemnt #120 Programs That Write to Files

Code


    /// Name: JJ Deng
    /// Period: 6
    /// Program Name: Programs That Write to Files
    /// File Name: Receipt.java
    /// Date Finished: 5/23/2016
 
    import java.util.Scanner;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.InputMismatchException;
    
    public class Receipt {
    
        public static void main(String[] args) {
    
            PrintWriter fileOut;
            float PPG = 4.99f; // Price Per Gallon
            float num = -1;
            
            do{
                try{
                    
                Scanner keyboard = new Scanner(System.in);
                
                System.out.print("How many gallons? ");
                num = keyboard.nextFloat();
                }
    
            catch(InputMismatchException e){
                System.out.println("ERROR");
            }
            } while (num < 0);
    
            try{
                fileOut = new PrintWriter("receipt.txt");
    
            } catch(IOException e) {
                System.out.println("Sorry, I can't open the file 'receipt.txt' for editing.");
                System.out.println("Maybe the file exists and is read-only?");
                fileOut = null;
                System.exit(1);
            }
    
            fileOut.println( "+------------------------+" );
            fileOut.println( "|                        |" );
            fileOut.println( "|     CORNER STORE       |" );
            fileOut.println( "|                        |" );
            fileOut.println( "| 2016-01-25 04:38PM     |" );
            fileOut.println( "|                        |" );
            fileOut.println( "| Gallons: "+num+"           |" );
            fileOut.println( "| Price/gallon: $ "+PPG+"   |" );
            fileOut.println( "|                        |" );
            fileOut.println( "| Fuel total: $ "+(num*PPG)+"     |" );
            fileOut.println( "|                        |" );
            fileOut.println( "+------------------------+" );
    
            fileOut.close();
            
            System.out.println("Printed");
        }
    }


    

Picture of the output

Assignment 120