Re: Scanner class and last line in a file
- From: DemonWasp <jda980@xxxxxxx>
- Date: Sun, 24 Sep 2006 21:11:03 -0400
On Sun, 24 Sep 2006 17:25:34 -0400, Lew <conrad@xxxxxxxxxxx> wrote:
<snip>
Scanner.hasNextLine()
"Returns true if there is another line in the input of this scanner. ... The
scanner does not advance past any input."
Scanner.nextLine()
"Advances this scanner past the current line and returns the input that was
skipped. 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."
In other words, nextLine() is supposed to return the text that was skipped.
I recognise this, but I probably didn't make it sufficiently clear in
my post. However, this wasn't the main issue.
If your input has only one line (or zero), the loop will not execute. The
initialization will read the one line, then the condition will fail because
there is no second line.
When the loop finished and you tried to call nextLine() again (assuming you
used the same Scanner instance), it threw the exception because hasNextLine()
had already failed. Calling nextLine() when ! hasNextLine() raises the exception.
Try something like:
Scanner in = new Scanner( inFile );
while ( in.hasNextLine() )
{
String line = in.nextLine();
// do something with line
}
(The convention is to name variables with a lower-case first letter.)
Yeah, but I'm unconventional :P. Again though, this example misses the
point of the question that I was asking.
What I *was* asking was "how do I get the last line from a file, even
when there is no trailing whitespace?"
Thanks anyway,
DemonWasp
.
- Follow-Ups:
- Re: Scanner class and last line in a file
- From: Mark Rafn
- Re: Scanner class and last line in a file
- From: IchBin
- Re: Scanner class and last line in a file
- References:
- Scanner class and last line in a file
- From: DemonWasp
- Re: Scanner class and last line in a file
- From: Lew
- Scanner class and last line in a file
- Prev by Date: Re: Scanner class and last line in a file
- Next by Date: Re: Scanner class and last line in a file
- Previous by thread: Re: Scanner class and last line in a file
- Next by thread: Re: Scanner class and last line in a file
- Index(es):
Relevant Pages
|
|