2012-11-22 17 views
0

我試圖在try-catch塊後聲明s.next(),但它不起作用!如果s位於try塊內,它將只有下拉菜單。掃描儀變量不能在try-catch塊外工作

我不想總結解析輸入,將所有適當的操作都放到try塊中,因爲它們不會拋出FNFE和IOE。我能在這裏做什麼?

public static void main(String[] args) 
     { 
     // TODO Auto-generated method stub 

     //Open file; file name specified in args (command line) 
     try{ 
      FileReader freader = new FileReader(args[0]); 
      Scanner s = new Scanner(freader); 

     }catch(FileNotFoundException e){ 
      System.err.println("Error: File not found. Exiting program..."); 
      e.printStackTrace(); 
      System.exit(-1); 
     }catch(IOException e){ 
      System.err.println ("Error: IO exception. Exiting..."); 
      e.printStackTrace(); 
      System.exit(-1); 
     } 
     // if i try to declare s.next() here it would not work 

回答

2

我想你的意思是你想使用 s.next(),它是行不通的。

要做到這一點,將s聲明爲try/catch塊外部的變量,並將其設置爲null。然後將其分配到現在分配的位置,但沒有聲明。如果我的假設是正確的,你的問題是s不再是try/catch之外的活動變量,因爲它在該塊內聲明。

FileReader freader = null; 
Scanner s  = null; 
try { freader = new FileReader(args[0]); // risk null pointer exception here 
     s = new Scanner(freader); 
    } 
catch { // etc. 
1

因爲s變量這是Scanner類的實例僅限於try塊。如果您希望s可以訪問外部try-catch塊,請在try catch外面聲明它。

Scanner s = null; 
try{ 
     FileReader freader = new FileReader(args[0]); 
     s = new Scanner(freader); 

    }catch(FileNotFoundException e){ 
     System.err.println("Error: File not found. Exiting program..."); 
     e.printStackTrace(); 
     System.exit(-1); 
    }catch(IOException e){ 
     System.err.println ("Error: IO exception. Exiting..."); 
     e.printStackTrace(); 
     System.exit(-1); 
    } 
1

在Java中,變量是由他們在聲明塊作用域。由於您的掃描儀是try塊內部構造,這是不是它的外部可見。

是否有任何理由想要在此區域之外進行實際的掃描操​​作?在Java 7中,一個常見的成語是試穿與資源模式:

try (Scanner s = new Scanner(new FileInputStream(file)) { 
    //Do stuff... 
} 

,它會自動關閉了掃描儀的資源。實際上,您可能會泄漏它,因爲代碼示例中沒有finally塊。