Reading and Processing Scanner File Input
Assignment: Write a program to read a file whose data is a series of pairs of
tokens, where each pair begins with an integer value and is followed by the type of coin,
which will be pennies (1 cent each), nickels (5 cents each), dimes (10 cents each),
or quarters (25 cents each), case-insensitively. Your program should add up the cash
value of all the coins and then output the total amount of money. For example, if the
input file contains the text:
3 pennies 2 quarters 1 Pennies 23 NiCKeLs 4 DIMES
your program would output Total money = $2.09
Note: input file will have pairs of tokens, but there could be dupilicate coins specified (like pennies above), and some lines will not have each of the possible types of coins.
|
public class CountCoins {
public static boolean trace = false;
public static void processFile (Scanner input) {
int coins = 0;
String coin_type = "";
double total = 0.0;
while (input.hasNextLine()) {
String line = input.nextLine();
// split the line into an array of words parsing and whitespace
String[] arr = line.split("\\s");
if (trace)
for (int j=0; j< arr.length; j++)
System.out.println("Trace token["+j+"] = " + arr[j]);
total = 0.0;
int i = 0;
while(i < arr.length) {
coins = Integer.parseInt(arr[i]);
i++;
if (i < arr.length) { // get coint type
coin_type = arr[i].toLowerCase();
if (coin_type.equals("pennies"))
total = total + 0.01*coins;
else if (coin_type.equals("nickels"))
total = total + 0.05*coins;
else if (coin_type.equals("quarters"))
total = total + 0.25*coins;
else if (coin_type.equals("dimes"))
total = total + 0.10*coins;
else
System.out.println("Unknown coin type ignored: "+coin_type);
i++;
if (trace)
System.out.printf(" subTotal Money = $%1.2f \n",total);
} // processing the line of input
} // expecting 10 entries, of 5 pairs of # coin-type - process in pairs
System.out.printf("Total Money = $%1.2f \n",total);
} // while
}
public static void main(String[] args) {
fileUtils a = new fileUtils();
CountCoins b = new CountCoins();
Scanner sc = null;
if (args.length > 0) {
if (b.trace)
System.out.println("arglen = " + args.length + " " + args[0]);
sc = a.getScanner(args[0]);
}
else
sc = a.getScanner("");
b.processFile(sc);
sc.close();
} // main
} // CountCoins
|
|
processFile was called from the main program. The main program begins by seeing if a file name was specified on the command line, if so, that file name is used to process a file, otherwise the user is prompted to specify the name of a file to process. The program was run with the file
coin.data which contains:
5 pennies 3 dimes
2 pennies 2 nickels 2 quarters 2 pennies 9 dimes 12 pennies
3 pennies 2 quarters 1 Pennies 23 NiCKeLs 4 DIMES
Here is a sample program run :
|