2013-03-03 126 views
0

我想有用戶輸入一個整數,根據整數值,我打電話混合功能的文件內容讀取,代碼如下所示。我越來越,這個錯誤:無法讀取文件在Java中

Project2.java:43: variable urlScan might not have been initialized 
         while (urlScan.hasNext()) 
          ^
Project2.java:34: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 
       fileScan = new Scanner (new File("input.txt")); 
        ^

任何想法,我可能在這裏做錯了嗎?

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

public class Project2 
{ 
    public static void main(String[] args) 
    { 

       System.out.println("Select an item from below: \n"); 
       System.out.println("(1) Mix"); 
       System.out.println("(2) Solve"); 
       System.out.println("(3) Quit"); 

       int input; 
       Scanner scan= new Scanner(System.in); 
       input = scan.nextInt(); 

       System.out.println(input); 
       if(input==1) { 
        mix(); 
       } 
       else{ 
        System.out.println("this is exit"); 
        } 
     } 




     public static void mix() 
      { 
       String url; 
       Scanner fileScan, urlScan; 
       fileScan = new Scanner (new File("input.txt")); 
       // Read and process each line of the file 
       while (fileScan.hasNext()) 
        { 
         url = fileScan.nextLine(); 
         System.out.println ("URL: " + url); 
         //urlScan = new Scanner (url); 
         //urlScan.useDelimiter("/"); 
         // Print each part of the url 
         while (urlScan.hasNext()) 
         System.out.println (" " + urlScan.next()); 
         System.out.println(); 
        } 
      } 
    } 
+2

的錯誤是很清楚... – Reimeus 2013-03-03 23:03:04

+1

您是否嘗試過谷歌? - [第一](https://www.google.com/search?q=java+variable+might+not+have+been+initialized+stackoverflow),[second](https://www.google.com/搜索q = java的+未報告+異常+必須要+ + +抓到+或聲明+到+被拋出+計算器+) – Dukeling 2013-03-03 23:06:05

回答

3

這些錯誤非常有表現力。

  • 初始化您urlScan局部變量(局部變量沒有得到默認值)
  • 包裹fileScan = new Scanner (new File("input.txt"));各地try/catch。或者聲明你的方法可能在你的方法簽名中拋出FileNotFoundException。 (新文件(STR)可能會拋出FileNotFoundException這是一個檢查的異常和編譯器會強迫你處理吧)。
+2

或者更好的,因爲你不知道如何在混合方法對付一個IOException,申報它在拋出子句中。 – 2013-03-03 23:03:49

1

首先,urlScan未初始化。

其次,你應該圍繞fileScan = new Scanner (new File("input.txt"));用try/catch語句的FileNotFoundException

1

局部變量必須初始化使用前,所以取消這一行:

urlScan = new Scanner (url);