I have the following code and an input file that has all numbers such that each line in the txt file has only one number. I print each number on each line onto standard out and I stop printing if I encounter the number 42. But the problem is my scanner object which i’m using to read the file is not displaying the first number and is only printing from the second number of my txt file. I think this has something to do with the scanner.nextline function I don’t know but I wish scanner had a getcurrent or something like that to make things simpler. Anyway could anyone please tell me how to solve this problem and get the first line to display.
Here’s my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class driver {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File theFile = new File("filepath.../input.txt");
Scanner theScanner = new Scanner(theFile);
//so that the scanner always starts from the first line of the document.
theScanner.reset();
while(theScanner.hasNext())
{
if(theScanner.nextInt() == 42)
{
break;
}
System.out.println(theScanner.nextInt());
}
}
}
I was calling the nextInt() method twice on the scanner object before I printed out to standard output. Once in the if statement and again in the System.out.println. Hence the scanner started printing from the second line of the txt file.
But the solution would be including a line of code like the following:
before the if statement and then modifying the if statement to :