Saving Caferia Prices - text file

  Download Source Code

/***********************************************
The school cafeteria sells food to about 1000 students
each day. They have a program to record the amount paid
for each transaction. The result is a text file on
the disk containing all the numbers paid each day.
************************************************/


import java.io.*; public class PricesSaver { double[] nums = new double[10000]; int count = 0; // number of items in NUMS public PricesSaver() { double price = 0; while(price >= 0) // type -1 at the end of the day { price = Double.parseDouble( input("Price") ); if(price >= 0) { nums[count] = price; count = count+1; } } saveNumbers(); stats(); } void saveNumbers() { try { BufferedWriter file = new BufferedWriter( new PrintWriter("prices.dat") ); for(int c=0; c < count; c = c+1) { file.write(nums[c]+"\n"); } file.close(); } catch(IOException ex) { System.out.println(ex.toString()); } } void stats() { double sum = 0; for(int c=0; c < count; c = c+1) { sum = sum + nums[c]; } System.out.println("Total = " + sum); System.out.println("Average = " + sum / count); } public static void main(String[] args) { new PricesSaver(); } public String input(String prompt) { return javax.swing.JOptionPane.showInputDialog(null,prompt); } public void output(String message) { javax.swing.JOptionPane.showMessageDialog(null,message); }
}

PrintWriter

PrintWriter is a standard Java class.  The Processing command createWriter("prices.dat") creates a PrintWriter Object,
based on the standard class.  The program names uses file as a name for this Object.
The file object contains a .println method that can write data into the "prices.dat" file.  This println method works
just like the normal println command, except that the data is printed into the file rather than being printed into
the black console window.  This program uses a loop to print a list of all the prices into the data file.

When the program ends, it writes all the prices into the data file.  You can find the actual data file
in the "Sketch Folder" - use the Sketch menu to open this folder.  Now you can open the prices.dat file
with Notepad (or any other text editor) and you will see that it contains all the prices.
This means that the cafeteria can keep a permanent record of all the prices that were charged during the day.

Programming Practice