Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. /*
  2.  * Input: A string of the csv filename (with .csv extension) that has 2 columns.
  3.  * Output: A multidimensional array of strings, where the first index is the abbreviation,
  4.  *         the second index is the full value
  5.  * O(m) Runtime, where m is the number of abbreviations
  6.  * O(2m) -> O(m) Storage, where m is the number of abbreviations
  7.  *
  8.  * CAN ONLY HANDLE 100 Abbreviations
  9.  */
  10. public static String[][] csvToArray(String csvName) {
  11.     String[][] csvArray = new String[100][2];  // create a multidimensional array that can hold 100 abbreviations
  12.  
  13.     try {
  14.         BufferedReader reader = new BufferedReader(new FileReader(csvName));
  15.         reader.readLine();                                           // read first line to remove column titles
  16.  
  17.         String row;
  18.         int index = 0;
  19.  
  20.         // O(m) runtime, where m is the number of lines(abbreviations)
  21.         while ((row = reader.readLine()) != null) {                  // read until end of file
  22.             String[] kv = row.split(",");                     // split the row into col 1 and 2 based on ,
  23.             csvArray[index][0] = kv[0];                             // set first index to the abbreviation
  24.             csvArray[index][1] = kv[1];                             // set second index to the full value
  25.             index++;
  26.         }
  27.  
  28.         return csvArray;
  29.  
  30.         // Catch Exceptions
  31.     } catch(FileNotFoundException e) {
  32.         System.out.println(String.format("Cannot Find %s", csvName));
  33.     } catch (IOException e) {
  34.         System.out.println("Error Reading File");
  35.     } catch (IndexOutOfBoundsException e) {
  36.         System.out.println("Too Many Abbreviations");
  37.     }
  38.  
  39.     // If exception is caught, set first index to null
  40.     csvArray[0][0] = null;
  41.     return csvArray;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement