Re: Scanner class and last line in a file
- From: dagon@xxxxxxxxx (Mark Rafn)
- Date: Mon, 25 Sep 2006 11:31:43 -0700
DemonWasp <jda980@xxxxxxx> wrote:
I've been having some trouble getting the Scanner class to operate the
way I'd like.
Came back to read the OP to see what I'd missed. You misstate the problem.
It's not the Scanner doing the wrong thing, you're confused about how a for()
loop works.
for ( Ln=In.nextLine() ; In.hasNextLine() ; Ln=In.nextLine() ) {
// Do stuff with Ln in here.
}
Remember,
for( a; b; c) { d }
is exactly translatable as
{ a; while (b) { d; c; }
I'm unwilling to put up with stupidly nonstandard naming, so I'll just pretend
your variables are lowercase. Your code is identical to:
ln=in.nextLine();
while (in.hasNextLine) {
// do stuff
ln = in.nextLine();
}
This is just wrong. You're getting line 0, then test for line n+1 before
processing line n and getting n+1. You'll blow up with empty input, and skip
processing the last line. You'll GET the last line, as the last part of
processing the previous, but your loop condition is now false, so you won't
process it.
Unfortunately, this moves the "cursor" in the file down one line, and
returns the text skipped - probably not what I was trying to do. Also,
when it gets to the end of the file, hasNextLine() returns false (as
it should) and the loop finishes. Unfortunately, it's still left
precious information in the file!
Nope, it left the information in your ln variable.
When I tell it to load the final line using nextLine(), it tries
advancing past the end of the file and gives me a
NoSuchElementException.
As it should. You already read the last line, you just haven't processed it
yet.
How can I get that last line (preferably, using the Scanner class)? Is
it possible to specify that the EOF sequence is a delimiter - or would
that even work?
You _ARE_ getting the last line. you're just discarding it by getting it at
the end of your loop rather than the beginning. try the following:
in = new Scanner(input);
while (in.hasNextLine) {
ln = in.nextLine();
// do stuff
}
or (if you want your locals to conveniently go out of scope after the loop
for (in = new Scanner(input); in.hasNextLine; ) {
String ln = in.nextLine;
// do stuff
}
--
Mark Rafn dagon@xxxxxxxxx <http://www.dagon.net/>
.
- References:
- Scanner class and last line in a file
- From: DemonWasp
- Scanner class and last line in a file
- Prev by Date: Re: Scanner class and last line in a file
- Next by Date: Re: beginner's question
- Previous by thread: Re: Scanner class and last line in a file
- Next by thread: Error?
- Index(es):
Relevant Pages
|
|