【发布时间】:2015-06-29 00:13:58
【问题描述】:
我需要编写一个程序来读取文本文件并计算不同的东西,但是,如果找不到文件名,它应该打印一条错误消息,其中包含来自 try 和 catch 块的以下错误消息:
java.io.FileNotFoundException: inputValues (The system cannot find the file specfied)
.......
但是,我收到了以下错误消息:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:50)
这是我的部分代码:
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: "); // Prompts User to Enter Input File Name
String inputFileName = console.nextLine(); // Reads Input File Name
Scanner in=null; //
try
{
in = new Scanner(new File(inputFileName)); // Construct a Scanner Object
}
catch (IOException e) // Exception was Thrown
{
System.out.print("FileNotFound Exception was caught, the program will exit."); // Error Message Printed because of Exception
e.printStackTrace();
}
int n = in.nextInt(); // Reads Number of Line in Data Set from First Line of Text Document
double[] array = new double[n]; // Declares Array with n Rows
第 50 行是: int n = in.nextInt();
除了打印不正确的错误信息外,我的程序运行良好。
任何/所有帮助将不胜感激!
【问题讨论】:
-
找到文件但文件内容不是int
-
那么我该如何更改它以仅打印 FileNotFound 异常??
-
下面
in为空时从方法返回、退出程序或以其他方式处理。如果操作失败,则无法获取下一个数字。 -
无论如何,文件 is 已找到,但 not 包含一个“整数”作为第一个元素。如果它实际上抛出了 FNFE,那么
in将为空。这就是 actual InputMistmatchException 的意思。