![](/img/trans.png)
[英]java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?
[英]Wrong logic in using scanner. The first line of the text file is not printed out to stdout
我有以下代码和一个具有所有数字的输入文件,因此txt文件中的每一行只有一个数字。 我将每行上的每个数字打印到标准输出上,如果遇到数字42,则停止打印。但是问题是我用来读取文件的扫描仪对象未显示第一个数字,而仅从第二个开始打印我的txt文件编号。 我认为这与我不知道的scan.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());
}
}
}
问题是您在检查时正在读一个数字,然后再读一个打印出的新数字。 这意味着您将每隔两个数字打印一次。 要解决它,只需先存储数字:
int number = theScanner.nextInt()
if(number == 42)
{
break;
}
System.out.println(number);
在打印到标准输出之前,我两次在扫描程序对象上调用nextInt()方法。 一次在if语句中,再一次在System.out.println中。 因此,扫描仪从txt文件的第二行开始打印。
但是解决方案将包括如下代码行:
int temp = theScanner.nextInt();
在if语句之前,然后将if语句修改为:
if(temp == 42)
{
break;
}
System.out.println(temp);
注意您调用了nextInt()方法有多少次。 即两次,因此您的代码必须跳过文件中的所有其他整数。 (如果仅从文件读取两个整数,则仅第一个数字)
因此,最简单的解决方案是将整数存储在局部变量中,然后使用它进行比较和打印。
即:
while(theScanner.hasNext())
{
int nextInteger=theScanner.nextInt();
if(nextInteger == 42)
{
break;
}
System.out.println(nextInteger);
}
theScanner.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.