我有一个我需要读取的文件,打印出整数,捕获异常并继续显示下一个整数,依此类推,直到没有更多的整数.
该文件包含:12 5 sd 67 4 cy
我希望它显示:
12
5
输入错误
67
4
输入错误
但是,它只给我12,5,然后输入错误,它停止.我已经尝试将所有内容放入while循环中,并且无限循环地输入异常.
public static void readNumbers()
{
File inputFile = new File ("C:/users/AC/Desktop/input.txt");
try
{
Scanner reader = new Scanner(inputFile);
while(reader.hasNext())
{
int num = reader.nextInt();
System.out.println("Number read: " +num);
}
}
catch (InputMismatchException e)
{
System.out.println("Input error ");
}
catch (FileNotFoundException e2)
{
System.out.println("File not found!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么,以便循环继续读取下一个int等等?