我需要編寫一個程序來讀取文本文件並計算不同的東西,但是,如果未找到文件名,它應該打印一條錯誤消息,其中包含以下錯誤消息catch塊:在Java中嘗試並捕獲錯誤
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異常? – coscdummy
從方法返回,退出程序,或以其他方式處理下'in'爲null時。如果操作失敗,則無法獲取下一個號碼。 – user2864740