Sing Sandibar
Sing Sandibar

Reputation: 714

nextLine() ignoring delimiter "\\n"

I am reading input from a file where text is seperated by one or more newlines. To ignore blank newlines I use input.useDelimiter("\\n"); But for some reason the nextLine()-method reads the blank lines instead of ignoring them. What am I doing wrong?

Edit: Assume that the first line is a blank newline, and the second line has the string "ABC"

    input.useDelimiter("[\n]+");
    String kjkj = input.nextLine();
    System.out.println("***"+kjkj+"***");

Gives this result: ****** Instead of ***ABC***

Upvotes: 3

Views: 6052

Answers (1)

DirkyJerky
DirkyJerky

Reputation: 1168

Scanner#nextLine() Does not use the delimiter pattern, it used its own internal one to check for every instance of a new line.

To fix it, use Scanner#next() with a delimiter pattern "\\n+" to check for multiple new lines in a row.

// Change the delimiter to the newline char
// \\r used just for Windows compatibility
input.useDelimiter("[\\r\\n]+");
// Get the next non-blank line
String nextLineThatHasSomething = input.next();

Upvotes: 8

Related Questions