1 import java.io.File;
2 import java.io.FileNotFoundException;
3 import java.io.PrintWriter;
4 import java.util.Scanner;
5
6 /**
7 This program reads a file whose lines contain items and prices,
8 like this:
9 item name 1: price 1
10 item name 2: price 2
11 ...
12 Each item name is terminated with a colon.
13 The program writes a file in which the items are left-aligned
14 and the prices are right-aligned. The last line has the total
15 of the prices.
16 */
17 public class Items
18 {
19 public static void main(String[] args) throws FileNotFoundException
20 {
21 // Prompt for the input and output file names
22
23 Scanner console = new Scanner(System.in);
24 System.out.print("Input file: ");
25 String inputFileName = console.next();
26 System.out.print("Output file: ");
27 String outputFileName = console.next();
28
29 // Construct the Scanner and PrintWriter objects for reading and writing
30
31 File inputFile = new File(inputFileName);
32 Scanner in = new Scanner(inputFile);
33 PrintWriter out = new PrintWriter(outputFileName);
34
35 // Read the input and write the output
36
37 double total = 0;
38
39 // We read a line at a time since there may be spaces in the item names
40 while (in.hasNextLine())
41 {
42 String line = in.nextLine();
43 boolean found = false;
44 String item = "";
45 double price = 0;
46 for (int i = 0; !found && i < line.length(); i++)
47 {
48 char ch = line.charAt(i);
49 if (ch == ':')
50 {
51 found = true;
52 item = line.substring(0, i + 1);
53 price = Double.parseDouble(line.substring(i + 1).trim());
54 total = total + price;
55 }
56 }
57 // If no colon was found, we skip the line
58 if (found)
59 {
60 out.printf("%-20s%10.2f\n", item, price);
61 }
62
63 }
64
65 out.printf("%-20s%10.2f\n", "Total:", total);
66
67 in.close();
68 out.close();
69 }
70 }