Reputation: 77
So I want scanner to analyze each line of a text file and stop after an x amount of words, in this case x=3.
My code looks something like this :
scannerName.nextLine();
scannerName.next();
scannerName.next();
scannerName.next();
Well, the problem here is that nextLine() advances the scanner past the current line AS WELL AS return a string. So if I call next(), that will just find the next string which is on the next line (right?).
Is there a way to do what I'm asking?
Thank you
Upvotes: 0
Views: 787
Reputation: 1163
Your question is not so precise, but i have a solution for reading from txt-files:
Scanner scan = null;
try {
scan = new Scanner(new File("fileName.txt"));
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException: " + ex.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
int wordsRead = 0;
int wordsToRead = 3; //== You can change this, to what you want...
boolean keepReading = true;
while (scan.hasNext() && keepReading) {
String currentString = scan.nextLine(); //== Save the entire line in a String-object
for (String word : currentString.split(" ")) {
System.out.println(word); //== Iterates over every single word - ACCESS TO EVERY WORD HAPPENS HERE
wordsRead++;
if (wordsRead == wordsToRead) {
keepReading = false; //== makes sure the while-loop will stop looping
break; //== breaks when your predefined limit is is reached
} //== if-end
} //== for-end
} //== while-end
Let me know if you have any questions :-)
Upvotes: 1
Reputation: 1354
Try the following code : - while(scannerName.hasNext() != null) {
scannerName.next(); //Returns the 1st word in the line
scannerName.next(); //Returns the 2nd word in the line
scannerName.next(); //Returns the 3rd word in the line
//Analyze the word.
scannerName.nextLine();
}
Upvotes: 1