Package part2

Source Code of part2.CellStaticMethods

// ------------------------------------------------------------------
// Name and ID: Amit Malhotra (5796997)
// Comp 249
// Assignment #4 Part 2
// Due Date: 12 of April 2013
//--------------------------------------------------------------------

package part2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

/**
* This class contains our static methods used for the driver
* CellListUtilization.java
*
* @author Amit
*
*/
public abstract class CellStaticMethods {

 
  public static Scanner kb = new Scanner(System.in);
 
  /**
   * This method loads an object of the type File and attempts to open it
   * using the Scanner class for further processing.
   *
   * @param f an object of the type File
   * @return an object of the type Scanner
   */
  public static Scanner openFile(File f) {

    Scanner inputFile = null; // declare our Scanner variable outside the
                  // try-catch block

    if (!f.exists()) {
      System.out
          .println("The file you are attempting to import does not exist.");
      System.out.println("The program will now terminate. Goodbye");
      System.exit(0);
    } else {

      try {
        // create our new Scanner Object with Input File
        inputFile = new Scanner(new FileInputStream(f.getName()));

      } catch (FileNotFoundException e) {
        System.out.println("There was a problem with the file "
            + f.getName());
        e.printStackTrace();
      } catch (Exception e) {
        System.out.println("There was an error reading from the file "
            + f.getName());
        e.printStackTrace();
      }
    } // close if-else

    return inputFile; // our program must remember to close the file after
              // working with it
  } // close loadFile()

  /**
   * This method takes a opened Scanner file and an object of the class CellList
   * and fills it with the content read from the file
   *
   * @param inputFile  Opened Scanner File containing CellPhone objects
   * @param list A CellLst
   */
  public static void createList(Scanner inputFile, CellList list) {
    // File Format: serial number, brand, price, year
    // we will read our file and create CellPhone objects from it

    // lets create our phone variables, we will parse each line from
    // the file in these variables
    long serial = 0;
    String brand = "";
    double price = 0;
    int year = 1900;
    serial = inputFile.nextLong();
    brand = inputFile.next();
    price = inputFile.nextDouble();
    year = inputFile.nextInt();
    // create our head
    list.addToStart(new CellPhone(serial, brand, year, price));

    while (inputFile.hasNextLine()) {
      inputFile.nextLine(); // get to our next line
      // parse everything for our next cellphone object
      serial = inputFile.nextLong();
      brand = inputFile.next();
      price = inputFile.nextDouble();
      year = inputFile.nextInt();
      // if it is not a duplicate serialnumber, add it
      if (!list.contains(serial, false)) {
        list.addToStart(new CellPhone(serial, brand, year, price));
      } // end if
    } // end while

  } // end createList()
 
  /**
   * This method asks user for a file name, checks if the filename exists and returns
   * the File object with that name for further processing.
   *
   * @return  an object of the type File
   */
  public static File askOutputFile(){
   
   
    boolean validName = false; // flag to check for validfilename
    String name = ""; //to store our file name the user enters
    File n = null//initialize our file variable
    String response = "";
   
    // ask user for an Input file name
    System.out.print("\nPlease Enter a name for the output file:");

    // our loop will check if the user entered a valid file name or not
    while (!validName) {
      try {
        name = kb.next();
        n = new File(name); // new File object with the name user provided
        if (n.exists()) { // check if a file with that name already exists

          System.out.println("Error: The file " + name + " already exists.");
          // ask again
          System.out.println("Would you like to override this file?");
          response = kb.next();
          while ((response.charAt(0) != 'y') && (response.charAt(0) != 'n')){
            System.out.println("Please enter either a 'y' or a 'n' only: ");
            response = kb.next().toLowerCase();
          }
          if (response.charAt(0) == 'n'){
            System.out.print("Please Enter another name for the input file:");
          } else {
            validName = true;
          }
        } else {
          validName = true; // our flag to end our loop
        } // close if-else

      } catch (InputMismatchException e) {
        kb.nextLine(); // catch remove junk
        System.out.println("An error was encountered, please try again.");
      } catch (Exception e) {
        kb.nextLine(); // catch remove junk
        System.out.println("An error was encountered with the file name you entered, please try again.");
      }

    } // close while loop
   
    return n; //return the name of the file

  } // close askOutputFile() method
 

  /**
   * This method asks a user to enter a series of Serial Numbers (until the users
   * enters "n" to stop the loop) and then adds them to an ArrayList and returns
   * the ArrayList.
   *
   * @return  ArrayList<Long>
   */
  public static ArrayList<Long> askSerialNumber() {

    boolean done = false; boolean validNumber = false;
    ArrayList<Long> listOfSerials = new ArrayList<Long>();
    long serialNum;
    String response;
   
    // ask user for as many Serial Number he/she wants to give
    System.out.println("\nLet's take a few serial numbers and carry out a search.");
   
    // our loop will check if the user entered a valid number or not
    while (!validNumber || !done) {
      try {
        System.out.println("Please Enter a serial number: ");
        serialNum = kb.nextLong();
        //if no input error happened, below code will execute
        validNumber = true;
        System.out.println("Would you like to add more serial numbers? (y/n)");
        response = kb.next().toLowerCase();
        while ((response.charAt(0) != 'y') && (response.charAt(0) != 'n')){
          System.out.println("Please enter either a 'y' or a 'n' only: ");
          response = kb.next().toLowerCase();
        }
        if (response.charAt(0) == 'n'){
          done = true;
        }
        //if we made it here, then all went as planned
        listOfSerials.add(serialNum);
     
      } catch (InputMismatchException e) {
        kb.nextLine(); // catch remove junk
        System.out.println("An error was encountered, the number was not saved, please try again.");
      } catch (Exception e) {
        kb.nextLine(); // catch remove junk
        System.out.println("An error was encountered with the file name you entered, please try again.");
      }
    } // close while loop
    return listOfSerials; // return the serialNumber List
  } // close askSerialNumber() method
 
  /**
   * This method accepts a File Object and an ArrayList of numbers(long) and
   * saves that ArrayList in a file wth the name of the File Object.
   *
   * @param f  (File name to save)
   * @param list (list of numbers(long))
   */
  public static void saveToFile(File f, ArrayList<Long> list){
    PrintWriter out = null; //create a printWriter object
    try {
      out = new PrintWriter(new FileOutputStream(f)); //open file
      for ( long serialnum : list){ //ready from ArrayList
        out.print(serialnum + " "); //write
      }
     
    } catch (FileNotFoundException e){
      System.out.println("There was a problem creating file for output");
      e.printStackTrace();
    } finally {
      out.close();
    }
   
  } //end saveToFile
 
  /**
   * This method conducts a search on a list of CellPhones (object of CellList)
   * reading the serial numbers from a file.   It will indicate how many
   * iterations it took to find the object.
   *
   * @param f  name of the File
   * @param list  a linked list of cellphone objects
   */
  public static void searchFromFile(File f, CellList list){
    //open our file
    Scanner inputFile = null;
   
    try{
      inputFile = new Scanner(new FileInputStream(f)); //open file
      while(inputFile.hasNextLong()){ //read numbers
        long serialNum = inputFile.nextLong();
        System.out.println("Searching for " + serialNum);
        if(list.contains(serialNum, true)){ //conduct search
          System.out.println("We found the Serial Number: " + serialNum + ".");
        } else {
          System.out.println("Sorry we were not able to find the Serial Number: " + serialNum + ".");
        }
       
      }
     
    } catch (FileNotFoundException e){
      System.out.println("There was a problem reading from the file");
    } finally {
      inputFile.close();
    }
  }//end searchFrom File
 
  /**
   * This method simply asks user to press enter to continue.
   * Useful for breaking our long outputs and getting user to interact.
   */
  public static void breakTime(){
   
    System.out.println("\nPress enter to continue with the testing of our methods and classes.");
    try {
    System.in.read();
    } catch (IOException e){
      e.printStackTrace();
    }   
  } //end breakTime()
 
}// end staticmethods class 
TOP

Related Classes of part2.CellStaticMethods

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.