/* Written by Jen Chen Updated on March the 4th, 2003 Copyrighted by Jen Chen */ import java.io.*; import java.util.*; public class File_IO5 { public static void main(String[] args) throws IOException{ String fname = null; if(args.length < 1){ fname = "Details.csv"; } else{ fname = args[0]; fname = fname.trim(); } BufferedReader in = null; try{ in = new BufferedReader(new FileReader(fname)); } catch(Exception e){ System.out.println("Unable to open the specified file!"); System.out.println(e); System.exit(1); } StringTokenizer st; int total = 1, linenum = 0, qty = 0; double price_unit = 0., sum = 0.; try{ in = new BufferedReader(new FileReader(fname)); String line = in.readLine(); //Read into the column header. We don't want to parse this header since some of the fields do not contain numerical values. System.out.println("---------------------------------------------------------------------"); System.out.println("Description\t\t\t" + "Unit price\t" + "Quantity\t" + "Total"); //Print our OWN column HEADER!!! (NOT from the .csv file) System.out.println("---------------------------------------------------------------------"); while(line != null){ linenum++; st = new StringTokenizer(line, ","); while(st.hasMoreTokens() && linenum > 1){ // linenum > 1 means to skip the header of String st2 = (String) st.nextToken(); //the Details.csv file. (it is String, thus it can't be PARSE!) st2 = st2.trim(); if(st.countTokens()%5 == 3) //Print the 2nd field of the .csv file (which is the product name) System.out.print(st2 + "\t"); if(st.countTokens()%5 == 2){ //Assume that there are 5 fields in this data file. Print the 3rd field price_unit = Double.parseDouble(st2); //Use price_unit = new Double(st2).doubleValue() if you'd like to run //on our campus Unix box. I believe that they still run the old JDK library, //thus it does not recognize the Double.parseDouble() method. System.out.print("$" + price_unit + "\t\t"); } if(st.countTokens()%5 == 1){ //Assume that there are 5 fields in this data file. Print the 4th field qty = Integer.parseInt(st2); System.out.print(qty); sum = price_unit*qty; System.out.println("\t\t$" + sum); } total++; } line = in.readLine(); } } catch(Exception e){ System.out.println(e); System.exit(0); } } //end of main() } //end of class File_IO5{}