次のコードと、txtファイルの各行に1つの番号しかないようなすべての番号を持つ入力ファイルがあります。各行の各番号を標準出力に印刷し、番号42に遭遇すると印刷を停止します。しかし、問題は、ファイルの読み取りに使用しているスキャナーオブジェクトが最初の番号を表示せず、2番目の番号からのみ印刷していることです。私のtxtファイルの番号。これはscanner.nextline関数と関係があると思いますが、わかりませんが、スキャナーにgetcurrentなどを追加して、作業を簡単にしたいと思います。とにかく、この問題を解決して最初の行を表示する方法を教えてください。
これが私のコードです:
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());
}
}
}