2017-05-15 65 views
-1

我得到的消息獲得「錯誤:無法找到符號」

" Example.java:21: error: cannot find symbol

Scanner finput = new Scanner(filed); 
           ^

symbol: variable filed

location: class Example "

當我請編譯我的程序。我試過看這個,但我不明白爲什麼我得到這個錯誤。

下面是代碼

public class Example 
{ 

public static void main(String[] args) throws Exception 
{ 
    java.io.File filer = new java.io.File("RESULT.txt"); 
    System.out.println("Choose the location of the data file"); 
    JFileChooser fileCh = new JFileChooser(); 
    if (fileCh.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
     java.io.File filed = fileCh.getSelectedFile(); 
    } 
    else { 
     System.out.println ("No file choosen."); 
     System.exit(1); 

} 
    Scanner finput = new Scanner(filed); 
} 
} 
+0

這是一個錯字,使用這個:'掃描儀finput =新的掃描儀(filer)'...你使用了'新的掃描儀(提交)' –

+2

@TimBiegeleisen你怎麼知道這是一個錯字?它可能意味着在'if'塊中聲明的'filed'。當然,這沒有任何意義,但也不一定要命名'File'變量,所以誰肯定知道OP的意圖。 – Andreas

+0

@Andreas是的,你可能是對的,他應該在'if'語句之外聲明'File'。仍然可以被認爲是一個錯字。 –

回答

0

如前所述,您需要在if語句之外移動filed變量的聲明。你的代碼可以是這樣的:

public static void main(String[] args) throws Exception { 
    java.io.File filer = new java.io.File("RESULT.txt"); 
    System.out.println("Choose the location of the data file"); 
    JFileChooser fileCh = new JFileChooser(); 
    java.io.File filed = null; 

    if (fileCh.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
     filed = fileCh.getSelectedFile(); 
    } else { 
     System.out.println("No file choosen."); 
     System.exit(1); 

    } 
    Scanner finput = new Scanner(filed); 
} 

現在它工作正常。

+0

明白了。謝謝! –

0

因爲filed正在從非法訪問範圍您收到此錯誤。嘗試在if語句之外定義java.io.File filed。或者,也許你想使用Scanner finput = new Scanner(filer)

+2

請不要回答錯字問題,只是投票結束他們:-) –