balut_tek balut_tek - 1 year ago 77
Java Question

useDelimeter(",") not working

I have a text file that holds data like this:


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


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

String course1 =;
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
but still gives me the same output. How can I fix this?

Answer Source

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 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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download