How do I reset my Scanner object ?
Code:
Scanner myScanner = new Scanner(new FileInputStream("c:/try.txt"));
int numberOfLines = 0;
int total = 0;
while(myScanner.hasNextLine())
{
myScanner.nextLine();
numberOfLines++;
}
myScanner.reset();
for(int i = 0; i<numberOfLines; i++)
{
if(myScanner.hasNextInt())
{
total = total + myScanner.nextInt();
}
else
{
System.out.println("I am in else!");
}
}
System.out.println();
System.out.println("Number of lines: " + total);
I have a file called try.txt and it has 3 lines of text in it:
1
1
1
What I am trying to do is,
get the number of the lines in it,
See if the nextline is an integer,
And if so, add it to sum.
But my problem is,
Since my scanner scans thru the file, it is already in the end of the file.
How can I get my Scanner object to the beginning of the file again?
doesn't seem to do anything ?
Re: How do I reset my Scanner object ?
BTW
my code results in:
I am in else!
I am in else!
I am in else!
Number of lines: 0
Re: How do I reset my Scanner object ?
Why not read in all the lines from the file and process them in memory instead of reading and rereading and rereading the lines.
Reading from a disk is much more expensive than looking through Strings in memory.
If the file is really hugh, then you might consider another way.
Re: How do I reset my Scanner object ?
I really want to reset my Scanner object.
Re: How do I reset my Scanner object ?
What methods are available in the Scanner class? Do any of them do what you want?
If there are none then there are none.
If you want to "rewind" the location where you are reading in a file then you will have to use a different class to do the reading.
You can always create a new instance of the Scanner class.
Re: How do I reset my Scanner object ?
As far as I know, you can't. But why bother? Why not simply read through the file with one while loop?
Re: How do I reset my Scanner object ?
Thanks.
Creating a new Object works.
I guess there is no reseting then.
Re: How do I reset my Scanner object ?
Again, no need to create a new object, no need to reset. Just read through once with a while loop.