本文介紹了捕獲異常并請求用戶重新輸入的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在創(chuàng)建一個打開然后讀取用戶指定的文件的程序,目前我擁有的代碼如下所示:
System.out.println("Enter the name of the file you want to open: ");
FileN = scan.nextLine();
// I want the program to return to this point here if an error has occured.
try
{
scan = new Scanner(new File (FileN));
}
catch(Exception e)
{
System.out.println("Could not find file" + e);
System.out.println("Please enter a valid file name: ");
}
我已經(jīng)在上面指定了我希望程序在代碼中返回的位置,我目前已經(jīng)嘗試創(chuàng)建一個循環(huán),然后使用Continue,但是它不會讓我在循環(huán)中嘗試。此外,我試圖創(chuàng)造一個新的空白,但它仍然不起作用。當(dāng)前,即使用戶輸入了無效的文件名,程序也會繼續(xù)運行。
我已經(jīng)搜索了答案,但只能找到與我想要的內(nèi)容相關(guān)的答案:Java – Exception handling – How to re-enter invalid input
還澄清了在循環(huán)中嘗試是什么意思;是的,這是可能的。但是,我想知道為了繼續(xù)在我的程序中工作,我是將try放入循環(huán)中,還是將循環(huán)放入try中?我已經(jīng)提到:Should try…catch go inside or outside a loop?
This is the error I’m currently getting with my latest code
推薦答案
如果您使用Exception,從它的本意是用來處理意想不到的事情的意義上來說,它會變得更容易一些。正如預(yù)期的那樣,不存在的文件并不是真正的例外。存在但無法打開的文件,或者正在打開但內(nèi)容為零的文件(即使它有1MB的內(nèi)容)是意想不到的事情,因此也是例外??紤]到不存在的文件的預(yù)期行為(因為它是由用戶鍵入的,而用戶可能鍵入不正確),您可以使用如下內(nèi)容:
boolean fileExists = false;
File newFile;
while(!fileExists) {
System.out.println("Enter the name of the file you want to open: ");
FileN = scan.nextLine();
newFile = new File(FileN);
fileExists = newFile.exists();
if (!fileExists) {
System.out.println(FileN + " not found...");
}
}
try {
Scanner scan;
scan = new Scanner(newFile);
... do stuff with the scanner
}
catch(FileNotFoundException fnfe) {
System.out.println("sorry but the file doesn't seem to exist");
}
這篇關(guān)于捕獲異常并請求用戶重新輸入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,