I specifically want to only use a comma as my delimiter to read a CSV file.
For instance, a program might read a person's name, clock-in, and clock-out times. The associated CSV file might contain:
John Doe, 09:00, 17:00
The program should be able to read three separate tokens:
"John Doe", "09:00", "17:00"
the code I have set up goes something like this:
/* main method */
public static void main(String[] args) throws FileNotFoundException {
// scanner object
Scanner get = new Scanner(System.in);
// set delimiter, read comma and single space as delimiter
get.useDelimiter(", ");
// prompt for file
System.out.println("Provide a file name:");
File employeeRecords = new File(get.nextLine());
get = new Scanner(employeeRecords);
// test run
// read: employeeName, clockIn, lunchIn, lunchOut, clockOut
// "Employee" is an object
Employee $1 = new Employee(get.next(), get.next(), get.next(), get.next(), get.next());
// .timeWorked is a method of the "Employee" object
System.out.println("\nEmployee $1: " + $1.name + ", minutes worked: " + $1.timeWorked);
}
However, the problem I get is whenever I provide the csv file, the scanner ignores the delimiter arguments I provided.
The csv file specifically only contains one line:
John, 07:59, 12:00, 12:31, 17:00
The tokens I get from the five get.next()
statements are:
"John,", "07:59,", "12:00,", "12:31,", "17:00"
which means that the print statement prints out
Employee $1: John,, minutes worked: -1443
Ignoring the obvious bug in minutes worked, is there a way to only use commas as the delimiter?
EDIT: Not sure how to mark a comment as the answer, or if it is possible, but my bug in question was my delimiter had been defined before redefining the scanner object, as Slaw points out.