/* * Intro to Programming CSE 1310 * University of Texas at Arlington */ package code23octf18; import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.Scanner; /** * * @author jcmtiernan */ public class Code23OctF18 { /** * @param args the command line arguments */ public static void main(String[] args) { String dataFile = "bookSciFiData3.txt"; File inputData = new File (dataFile); // where is the file variable created and where can NetBeans see it? Scanner inFile; int yearD = 0; int[] years = new int[50]; //^^^ default values for int arrays int[] covers = {0,0,0}; // [0] = H, [1] = P, [2] = S final int coverH = 0; final int coverP = 1; final int coverS = 2; double priceD = 0; //^^^ declare a price array double prices[] = new double[50]; String titleD = "", seriesD =""; String[] titles = new String[50]; //^^^NO default values for String arrays String[] series = new String[50]; for (int i=0; i< 50; i++) { titles[i] = ""; //^^^ default all strings to empty string NOT null series[i] = ""; } char coverD = ' '; String tempD; int earliestPubYr = 1439; int latestPubYr = 2018; int earliestYear = 3000; int latestYear = 0; int eYCounter = 0; int lYCounter = 0; int counter = 1; int numH = 0,numP = 0, numS = 0; int errCount = 0; double avgPriceD = 0; boolean dataValid = true; // --- 1. How is dataValid being used? boolean lineToRead = true; double highestPrice =0; // attaching input file to scanner in a try-catch try { inFile = new Scanner(inputData); } catch (FileNotFoundException fnfe) { inFile = new Scanner(System.in); System.out.println("\nInput file \""+dataFile+"\" was not found"); } Scanner inData = new Scanner(System.in); String inString = ""; String yearStr = ""; System.out.printf("\n%8s %-39s%7s %5s %-20s\n","Year", "Book Title","Price","Cover","Series Name"); System.out.println("____________________________________________________________________________________"); //while (inData.hasNext() && dataValid) // --- 2. Compare while, do-while, for //### read one line at a time; read as strings; do { // Read various pieces of data from file including title inString = inFile.nextLine(); inData = new Scanner(inString); //System.out.println("Read line ::"+inString+"::"); dataValid = true; lineToRead = true; yearStr = inData.next(); try // --- 3. Why is a try-catch being used here? { yearD = Integer.parseInt(yearStr); //System.out.println("In try yearD"); //yearD = inData.nextInt(); } catch (InputMismatchException ime) { dataValid = false; String yearError = inData.next(); System.out.println("****In line "+counter+" - Invalid year data: "+yearError); errCount++; } catch (NumberFormatException nfe) { dataValid = false; //String yearError = inData.next(); System.out.println("****In line "+counter+" - Cannot parse year data: "+yearStr); errCount++; } //System.out.println("in while, counter is "+counter+" and yearD is "+yearD); // error check input year if ((dataValid) && ((yearD > latestPubYr) || (yearD < earliestPubYr)) ) { dataValid = false; System.out.println("****In line "+counter+" - Invalid year: "+yearD); errCount++; } if (dataValid) { //System.out.println("in 1st dataValid before earliestYear"); //years[counter-1] = yearD; //System.out.println("Year "+(counter-1)+" is "+years[counter-1]); if (yearD < earliestYear) { earliestYear = yearD; eYCounter++; } if (yearD > latestYear) { latestYear = yearD; lYCounter++; } tempD = inData.next(); coverD = tempD.charAt(0); //System.out.println("coverD is "+coverD); inData.useDelimiter("-*[0-9]"); titleD = inData.next(); inData.reset(); titleD = removeBlanks(titleD); // --- 4. Method call //System.out.println("Title is *"+titleD+"*"); //titles[counter-1] = titleD; //priceD = inData.nextDouble(); try // --- 3. Why is a try-catch being used here? { //System.out.println("In try yearD"); priceD = inData.nextDouble(); } catch (InputMismatchException ime) { dataValid = false; priceD = -1; String yearError = inData.next(); System.out.println("****In line "+counter+" - Invalid price data: "+yearError); errCount++; } catch (NoSuchElementException nsee) { dataValid = false; priceD = -1; //lineToRead = false; System.out.println("****In line "+counter+" - No price present "); errCount++; } //System.out.println("in 1st dataValid before priceD < 0 and price is "+priceD); if (priceD < 0) { dataValid = false; System.out.print("****In line "+counter+" - Invalid price: "); System.out.printf("%.2f\n",priceD); errCount++; } // --- 6. Write methods to find highest and lowest price to be called in // else of this test. What variables are needed? highestPrice = findHighestPrice(priceD, highestPrice); } if (dataValid) { switch(coverD) // --- 3. Review switch: (test), {body}, case { // constant labels, colon, break;, default case 'H': { //numH++; covers[coverH]++; break; } case 'P': { //numP++; covers[coverP]++; break; } case 'S': { //numS++; covers[coverS]++; break; } default: { dataValid = false; System.out.println("****In line "+counter+" - Invalid cover type: "+coverD); errCount++; break; } } //System.out.println("in 2nd dataValid before avgPriceD"); avgPriceD = avgPriceD + priceD; seriesD = inData.nextLine(); seriesD = removeBlanks(seriesD); //System.out.println("Series is *"+seriesD+"*"); } //System.out.println("after counter increment: "+counter); if (!dataValid) { //System.out.println("in !dataValid"); /*if (lineToRead) { inData.nextLine(); } */ dataValid = true; } else { years[counter-1] = yearD; //^^^ moving assignment to here. Why? prices[counter-1] = priceD; titles[counter-1] = titleD; series[counter-1] = seriesD; System.out.printf("%2d%6d %-37s %8.2f %3c %-30s\n", counter, yearD, titleD, priceD, coverD, seriesD); } counter++; } while (inFile.hasNext() && dataValid) ; //yearD = inData.nextInt(); // --- 5. make method to print earliest and latest year messages yearInfo("earliest", earliestYear,eYCounter); yearInfo("latest",latestYear, lYCounter); System.out.println(""); //outputResults(highestPrice, covers[coverH], covers[coverP], covers[coverS], errCount, avgPriceD, counter); outputResults2(highestPrice, covers, errCount, avgPriceD, counter); System.out.println(""); printYearTitle(years, titles, prices, counter); /* System.out.printf("%2d%6d %-37s %8.2f %3c %-30s\n", counter-1, yearD, titleD, priceD, coverD, seriesD); */ System.out.println("\nPrinting out books published before 1980:"); for (int cntr = 0; cntr < counter-1; cntr++) { if ((years[cntr] < 1980) && (years[cntr] > 0)) System.out.println("Row["+(cntr)+ "]: Publication year is "+years[cntr]+" and title is "+titles[cntr]); } System.out.println("\nPrinting out books costing less than $10.00:"); for (int cntr = 0; cntr < counter-1; cntr++) { if ((prices[cntr] < 10.00) && (years[cntr] > 0)) System.out.println("Price is "+prices[cntr]+" and title is "+titles[cntr]); } System.out.println("\nPrinting out books with titles starting with \"The\":"); for (String ttl:titles) { if (ttl.startsWith("The")) System.out.println("Title is "+ttl); } System.out.println("\nBefore method call: EarliestYear is "+earliestYear); System.out.println("Before method call: prices[0] = "+prices[0]); double booksValue = totalBooksValue(prices, earliestYear); System.out.println("The total value of all the books is "+booksValue); System.out.println("\nAfter method call: EarliestYear is "+earliestYear); System.out.println("After method call: prices[0] = "+prices[0]); System.out.println("\nThe series titles with the word The in front"); for (String ttl:series) { System.out.println("Series Name is: "+ttl); } removeThe(series); System.out.println("\nThe series titles without the word The in front"); for (String ttl:series) { System.out.println("Series Name is: "+ttl); } } public static void removeThe(String[] names) { //for (String ttl:names) for (int i=0; i < names.length; i++) { if (names[i].startsWith("The")) { //System.out.println("Old ttl: "+names[i]); names[i] = names[i].substring(4); //System.out.println("ttl assignment is :"+names[i]); } } } public static double totalBooksValue(double[] cost, int year) { double total = 0; //for(int i=0; i < prices.length; i++) for (double price: cost) { //total = total + price; total += price; } year = 0; return total; } // --- 5. Write one method to print earliest year and latest year sentences public static void yearInfo(String whichMax, int year,int counter) { System.out.println("\nThe "+whichMax+" year is "+year + " with "+counter+" replacements"); } // Method to remove extra blanks and tabs from beginning and end of a string public static String removeBlanks(String inStr) { int inStrLen = inStr.length(); //System.out.println("initial inStr is *"+inStr+"*"); int i = 0; while ((inStr.charAt(i) == ' ') || (inStr.charAt(i) == '\t')) { inStr = inStr.substring(1); // remove one blank at front i=0; // make counter start at 0 again inStrLen = inStr.length(); // get length of new string } //System.out.println("middle inStr is *"+inStr+"*"); inStrLen = inStr.length(); i = (inStrLen - 1); while ((inStr.charAt(i) == ' ') || (inStr.charAt(i) == '\t')) { inStr = inStr.substring(0,i); // remove blanks at end i--; } //System.out.println("final inStr is *"+inStr+"*"); return inStr; } public static double findHighestPrice(double price, double highest) { if (price > highest) { highest = price; } return highest; } public static void outputResults(double highestPrice, int numH, int numP, int numS, int errCount, double avgPriceD, int counter) { System.out.println("--- Book list information ---\n"); System.out.println("Highest price was "+highestPrice); System.out.println("\nThere were "+numH+" hardbacks, "+numP +" paperbacks, and "+numS+" softcover books on the list"); System.out.printf("\nThe average price of a book on this list is $%.2f\n",(avgPriceD/counter)); System.out.println("\n**** "+errCount+" lines of input had errors"); //System.out.println("All data has been read"); System.out.println("\n--- Data is complete with "+counter+" books. ---\n"); } public static void outputResults2(double highestPrice, int[] num, int errCount, double avgPriceD, int counter) { System.out.println("+++ Book list information +++\n"); System.out.println("Highest price was "+highestPrice); System.out.println("\nThere were "+num[0]+" hardbacks, "+num[1] +" paperbacks, and "+num[2]+" softcover books on the list"); System.out.printf("\nThe average price of a book on this list is $%.2f\n",(avgPriceD/counter)); System.out.println("\n**** "+errCount+" lines of input had errors"); //System.out.println("All data has been read"); System.out.println("\n+++ Data is complete with "+counter+" books. +++\n"); } public static void printYearTitle(int[] years, String[] titles, double[] prices, int counter) { for (int cntr = 0; cntr < counter-1; cntr++) { System.out.println("Book["+(cntr)+ "]: Year is "+years[cntr]+", price is "+prices[cntr]+" and title is "+titles[cntr]); } } }