2013-03-02 68 views
0

我想寫一個簡單的程序,從文本文件中讀取整數,然後將總和輸出到輸出文件。我得到的唯一錯誤是在第38行的catch塊中「未解決的編譯問題:文件無法解析」。請注意,「文件」是我的輸入文件對象的名稱。如果我註釋掉這個異常塊,程序運行良好。任何意見,將不勝感激!從Java中的文件讀取時FileNotFoundException捕獲錯誤

import java.io.*; 
import java.util.Scanner; 

public class ReadWriteTextFileExample 
{ 
    public static void main(String[] args) 
    { 
     int num, sum = 0; 

     try 
     { 
      //Create a File object from input1.txt 
      File file = new File("input1.txt"); 
      Scanner input = new Scanner(file); 

      while(input.hasNext()) 
      { 
      //read one integer from input1.txt 
       num = input.nextInt(); 
       sum += num; 
      } 
      input.close(); 

     //create a text file object which you will write the output to 
     File output1 = new File("output1.txt"); 
     //check whether the file's name already exists in the current directory 
     if(output1.exists()) 
     { 
      System.out.println("File already exists"); 
      System.exit(0); 
     } 
     PrintWriter pw = new PrintWriter(output1); 
     pw.println("The sum is " + sum); 
     pw.close(); 
    } 
    catch(FileNotFoundException exception) 
    { 
     System.out.println("The file " + file.getPath() + " was not found."); 
    } 
    catch(IOException exception) 
    { 
     System.out.println(exception); 
    } 
}//end main method 
}//end ReadWriteTextFileExample 

回答

2

範圍是基於塊的。您在塊內聲明的任何變量只在該範圍內,直到該塊的結尾。

try 
{ // start try block 
    File file = ...; 

} // end try block 
catch (...) 
{ // start catch block 

    // file is out of scope! 

} // end catch block 

但是,如果你的try塊之前聲明file,它會留在範圍:

File file = ...; 

try 
{ // start try block 


} // end try block 
catch (...) 
{ // start catch block 

    // file is in scope! 

} // end catch block 
+0

好吧,這是有道理的。第一部分實際上是由教授給出的,所以我想我會畫一個箭頭移動try塊上方的一行。我不確定這是否是一個錯誤,或者我們是否應該抓住它。謝謝! – Johnny 2013-03-02 21:51:42

3

file變量在try塊內聲明。它在catch區塊範圍之外。 (雖然在這種情況下不可能發生,但想象一下,如果在執行之前拋出異常甚至到達變量聲明,基本上,您不能訪問catch塊中的變量,該塊在相應的try塊中聲明。)

你應該把它聲明之前try塊來代替:在Java中

File file = new File("input1.txt"); 
try 
{ 
    ... 
} 
catch(FileNotFoundException exception) 
{ 
    System.out.println("The file " + file.getPath() + " was not found."); 
} 
catch(IOException exception) 
{ 
    System.out.println(exception); 
}