Assignment #120: Programs that Write to Files

Code

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Receipt {

    public static void main(String[] args) {

        PrintWriter fileOut;
        double gal;
        double price = 2.75;
        
        Scanner kb = new Scanner(System.in);
        
        System.out.println("How many gallons of gas would you like to buy?");
        gal = kb.nextDouble();

        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("Gallons of fuel: " + gal);
        fileOut.println("Price per gallon: " + price);
        fileOut.println("Total price: " + (price * gal));
        
        fileOut.close();
    }
}
    

Picture of the output