Reputation: 17
I created a method using an ArrayList that is building a list from a CSV File. I am having trouble adding the String value of the field to the list. When I tried to use field.add() it gives me an error "The method add(String) is undefined for the type String". How do I fix this and make it so I can add the String value to the list and return the ArrayList?
/**
* This method begins by creating a new ArrayList of Strings. It then
* attaches a Scanner to the provided File object and uses a while
* loop to process the file line-by-line. For each line, this method creates
* a new Scanner object with a comma "," delimiter to to enable access the
* individual fields within the line using a second, inner while loop. As each
* field is processed it is tracked using a counter variable starting with
* field 1. If the current field is equal to the specified fieldFilter, the
* String value of the field is added to the list. Once all the lines in the
* file have been processed, the ArrayList is returned to the caller.
*
* If Scanner throws a FileNotFoundException when instantiating the new file
* Scanner object, catch the expection, display an error message, and exit
* the program immediately with an exit status of 1.
*
* @param csvFile File object that contains the CSV database to process
* @param fieldFilter Field number to use for building the list
* @return ArrayList of strings that represents the desired column of data from the database.
*/
public static ArrayList<String> buildListFromCSV(File database, int fieldFilter) {
final int ERROR_CODE = 1;
try {
Scanner fileScanner = new Scanner(database);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
int fieldCounter = 1;
while (lineScanner.hasNext()) {
String field = lineScanner.next();
if (fieldCounter == fieldFilter) {
field.add();
}
fieldCounter++;
}
lineScanner.close();
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("Unable to open file: " + database);
System.exit(ERROR_CODE);
}
return field;
}
Upvotes: 0
Views: 62