balut_tek balut_tek - 3 months ago 12
Java Question

useDelimeter(",") not working

I have a text file that holds data like this:

Jones,Mary,903452
4342,2.5,A
3311,4,B+


I'm using Scanner to read the file. This is my code:

while(reader.hasNextLine())
{
reader.useDelimiter(",");

String lastN = reader.next();
String firstN = reader.next();
String id = reader.nextLine();

String course1 = reader.next();
double credits = reader.nextDouble();
String grade = reader.nextLine();
}


But when I print the line on the console, the
,
on the last part of the line doesn't get delimited and it prints like this:

Jones, Mary, ,903452
4342, 2.5, ,A
6.5, ,3.569


My toString method on my class:

public String toString() {
return lastName + ", " + firstName + ", " + idNo + "\n"
+ courseOne + ", " + credits + ", " + grade;


I'm searched around for a solution. I tried
reader.useDelimiter("[,]")
and
reader.useDelimiter(",|,")
but still gives me the same output. How can I fix this?

Answer

From the Scanner's documentation:

This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

(Emphasis mine) This means that the whole rest of the line is returned, including delimiters. Setting id to reader.next() wouldn't work because it sucks up everything until the next delimiter. A better solution would be to make it accept line breaks as a delimiter, like so:

reader.useDelimiter("[,\n]");