import java.io.*;
import java.util.Scanner;
public class SalesOfCoffee{
// the next three variables are related to the scanner.
private static final String FILE_NAME = "coffee.csv";
private static Scanner myScanner;
// indicate if the scanner is valid or not.
private static boolean validScanner = false;
// so I can parse the input.
private static String line;
// class variables for each of the field of the input line
private static int id,
quantity;
private static float unitPrice,
totalCost;
private static String productCategory,
productType,
productDetail,
size,
day;
public static void main(String[] args){
int totalLines = 0;
String firstOfLine;
MakeScanner();
if (!validScanner) {
System.out.printf("Scanner not constructed\n");
return;
}
// skip the titles.
myScanner.nextLine();
while(myScanner.hasNextLine()) {
GetNextInput();
totalLines++;
PrintLineReport();
}
System.out.printf("The file contains %d lines.\n",totalLines);
myScanner.close();
}
private static void PrintLineReport(){
System.out.printf("On %s a customer purchased ", day);
System.out.printf("item %d:", id);
if (!size.equals("Not Defined")){
System.out.printf(" %s",size);
}
System.out.printf(" %s, %s, %s", productCategory,
productType, productDetail);
System.out.printf(" quantity %d @ $%.2f for a total of $%.2f\n", quantity,
unitPrice, totalCost);
}
private static void GetNextInput() {
line = myScanner.nextLine();
//System.out.printf("Got '%s'\n", line);
ParseLine();
}
private static void MakeScanner() {
try {
myScanner = new Scanner(new File(FILE_NAME));
validScanner = true;
} catch (FileNotFoundException e) {
System.out.printf("Cound not open %s", FILE_NAME);
}
}
// split an enter input line into the 9 components.
private static void ParseLine() {
id = IntSplitLine();
quantity = IntSplitLine();
unitPrice = FloatSplitLine();
totalCost = FloatSplitLine();
productCategory = SplitLine();
productType = SplitLine();
productDetail = SplitLine();
size = SplitLine();
day = line;
}
private static int IntSplitLine() {
String part;
int value = 0;
part = SplitLine();
value = Integer.parseInt(part);
return value;
}
private static float FloatSplitLine() {
String part;
float value = 0;
part = SplitLine();
value = Float.parseFloat(part);
return value;
}
// splits an input line into two parts based on , locations.
private static String SplitLine() {
String firstPart = "";
int position = 0;
position = line.indexOf(',');
if (position != -1) {
firstPart = line.substring(0, position);
line = line.substring(position+1);
}
return firstPart;
}
}