I have a scanner reading from a text file. When it gets to a certain line in the file, I want to be able to call a method that uses the Scanner as a parameter in its current state – as in, I want the scanner to be passed (along with the file used) at exactly what line it’s on.
public static void createEntry(File list, int mediaTypeNum, String mediaType) throws FileNotFoundException {
Scanner mediaReader = new Scanner(list);
int occurrence = mediaTypeNum;
int scannerCounter = 0;
String match;
String title = "";
String director = "";
while (mediaReader.hasNext() && scannerCounter < occurrence) {
match = mediaReader.nextLine();
if (match.equalsIgnoreCase(mediaType)) {
scannerCounter++;
if (scannerCounter == occurrence) {
// based on type, create the media object
// createMediaObject(list, mediaReader, mediaType)
title = mediaReader.nextLine();
director = mediaReader.nextLine();
}
}
}
createMediaObject() will have a switch case, and based on the case, the Scanner will read some following lines until there’s a blank line. For each media type, the number of lines differ.
Thank you in advance!
Of course, it is in fact true to any object in Java. No implicit copies of objects are created at any point.*
What you have to be careful about is that
Scannerhas a “sequential” state and if you’re passing it around a lot, it’s very easy to lose track of what state it is in. Especially if conditional processing is performed, where different execution paths might end up leaving it at different positions.A good approach to this is to always document in the method Javadoc what state the
Scanneris expected to be in and what state it’s left at the end.*There’s a big caveat to that statement: multithreading. But it would be highly off topic to discuss that here in detail.