From 583ecf2df556c0bb3ae5468a63d9231b3ef56f58 Mon Sep 17 00:00:00 2001 From: ArghKevin Date: Mon, 20 May 2024 05:42:37 -0700 Subject: Weeks 5 and 6. --- src/CSVReader.java | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) (limited to 'src/CSVReader.java') diff --git a/src/CSVReader.java b/src/CSVReader.java index fa588ef..3666531 100644 --- a/src/CSVReader.java +++ b/src/CSVReader.java @@ -17,14 +17,15 @@ import java.util.Arrays; */ public class CSVReader extends Reader { - String[] header; // A CSV file has-a header. One line, multiple fields. - /* Array of Hash map from header to value for each - line past the header. */ - ArrayList> body; // A CSV file has-a body. Multiple lines, multiple fields. + private String[] header; // A CSV file has-a header. One line, multiple fields. + // Array of HashMaps. Headers are keys, values are on each line of the CSV following the header. + private ArrayList> body; // A CSV file has-a body. Multiple lines, multiple fields. public CSVReader(File file) { super(file); // Call parent constructor + /* Construct the body to be filled. */ body = new ArrayList>(); + /* Parse the contents of the file, store in body. */ parse(); } @@ -32,26 +33,46 @@ public class CSVReader extends Reader { * Parse CSV file. */ public void parse() { + /* Split the input on newlines. */ String[] lines = this.getContents().split("\n"); + /* Split the first line by commas, assign to header array. */ this.header = lines[0].split(","); - /* Iterate over all lines of the body. */ + /* Iterate over all lines of the body. + First line is header, count from 1 instead of 0. */ for (int i = 1; i < lines.length; i++) { + /* Some lines have commas within parentheses. + Angkor,"/South East Asian (Thai, Khmer, Lao)/Looped",100 + Remove everything within parentheses. We need to escape + not on a language level, but on a function call level. + Double-backslash for a literal backslash, which is then + used to escape the parentheses in the regex library. */ + lines[i] = lines[i].replaceAll("\\(.*\\)", ""); + + /* CSV, Comma-Separated Values. */ String[] fields = lines[i].split(","); + /* Allocate a new HashMap for the given line of the CSV. */ HashMap map = new HashMap(); - /* For each of the columns, add the associated - value in this row. */ + + /* Associate each of the line's fields with its header. */ for (int j = 0; j < header.length; j++) { map.put(header[j], fields[j]); } + /* Add the HashMap to the list. */ body.add(map); } } + /** + * @return the length of the body. + */ public int getLength() { return body.size(); } + /** + * @return the value associated with the given key on the given line. + */ public String get(int i, String key) { return body.get(i).get(key); } -- cgit v1.2.3