2011-02-17 22 views
0
public static Scanner getFileScanner() 
{ 
    try{ 
     Scanner input = new Scanner(System.in); 
     String file = input.nextLine(); 
     Scanner fs = new Scanner(new FileReader(file));    
    }catch (FileNotFoundException fe) { 
     System.out.println("Invalid filename. Try another:"); 
     getFileScanner(); 
    }finally{ 
     return fs; 
    } 
} 

我一直收到找不到變量fs的錯誤。我無法弄清楚爲什麼我的生活。在java中遞歸地構建帶有嵌入式FileReader的掃描器

回答

1

fstry塊中聲明......解決這個問題,其聲明外塊: -

Scanner fs = null; 
try { 
    ... 
    fs = new Scanner(new FileReader(file)); 
} 
catch (FileNotFoundException fe) { 
    ... 
} 
finally { 
    return fs; 
} 
0

先聲明它:

public static Scanner getFileScanner() { 
    Scanner input = new Scanner(System.in); 
    Scanner fs = null; 
    while(fs == null) { 
     try{ 
      String file = input.nextLine(); 
      Scanner fs = new Scanner(new File(file));    
     }catch (FileNotFoundException fe) { 
      System.out.println("Invalid filename. Try another:"); 
     } 
    } 
    return fs; 
} 
0

您宣佈try塊FS並嘗試在不同的作用域(finally塊)中訪問它。通常的範例是在try塊之前聲明fs爲空。

1

try塊內聲明的變量不在相應的finally塊的範圍內。一般而言,您的方法存在許多問題......例如,finally區塊內的return通常不是個好主意。

這裏就是我想要做的:

public static Scanner getFileScanner() { 
    Scanner input = new Scanner(System.in); 
    File file = null; 
    while (true) { 
    file = new File(input.nextLine()); 
    if (file.exists() && file.isFile()) 
     break; 
    System.out.println("Invalid filename. Try another:"); 
    } 
    return new Scanner(new FileReader(file)); 
} 
0

只是對如何處理自己的代碼示例所示的其他球員展開......

因爲你聲明fs變量中的try塊中的變量只會在try關鍵字後面的大括號內限定(可見)範圍。

通過移動fs變量聲明出try塊和插入要確保變量可以由方法體(trycatchfinally塊)內的所有塊進行訪問的方法getFileScanner體。

希望有幫助!

1

讓我們通過列出在代碼中的問題開始:

  1. return語句編譯錯誤是由fs被淘汰的範圍,因爲在其他的答案中描述引起的。

  2. 當您遞歸調用getFileScanner()時,不會分配或返回結果。所以它不會讓它返回給調用者。

  3. finally塊中使用return壞主意。它會壓扁(扔掉)當時可能傳播的其他異常;例如與catch塊不匹配的例外或在catch塊中拋出的例外。

  4. 如果基礎流達到EOF,則input.nextLine()調用將引發異常;例如用戶輸入[CONTROL] + D或其他。你不需要必須捕獲它(它是未選中的),但finally塊中的返回將其壓扁(可能),導致調用者獲得null。呃...

  5. 硬接線System.inSystem.out使您的方法不易重複使用。 (好吧,這可能不是你應該解決的問題,而且我不會,下面...)

  6. 從理論上講,你的方法可以拋出StackOverflowError;例如如果用戶多次點擊[ENTER]。這個問題在遞歸解決方案中是固有的,並且不是這樣做的好理由。

最後,這裏有一個版本,解決這些問題的方法:

public static Scanner getFileScanner() throws NoSuchElementException 
{ 
    Scanner input = new Scanner(System.in); 
    while (true) { 
     String file = input.nextLine(); 
     try { 
      return new Scanner(new FileReader(file));   
     } catch (FileNotFoundException fe) { 
      System.out.println("Invalid filename. Try another:"); 
     } 
    } 
} 

請注意,我把它換成了遞歸,擺脫了對finally的,並宣稱被拋出的異常。 (人們可以捕獲該異常並將其報告或重新拋出,作爲特定於應用程序的例外。)