2015-08-19 153 views
-8
import java.io.*; 
public class FileApi extends File{ 
FileWriter fw; 
FileReader fr; 
PrintWriter pr; 

class public FileApi (String s) throws Exception 
{ 
    super(s); 
    pw = new PrintWriter(fw = new FileWriter(s, true)); 

} 

public void createFile() throws IOException 
{ 
    FileApi fa = new FileApi.createFile();   
    pw.println(fa);   
} 

public void createFile(String s) throws IOException 
{ 
    File fail = new File(s);       
    pw = new PrintWriter(fail);      
} 

public void WriteFile(String s) throws IOException 
{ 
    pw.println(s); 
    pw.flush(); 
} 

public String readFile() throws Exception 
{ 
    super(s); 
    fr = new FileReader(new File(s)); 
    String str=""; 
     int st; 

     while ((st = fr.read())!= -1) { 
      char ch=(char) st; 
      str=str+ch; 
     } 
     return str; 
} 

public void close() throws IOException 
{ 
    pw.close(); 
    fr.close(); 
    fw.close(); 
} 

public static void main(String [] arg) throws Exception 
{ 
    FileApi fileapi = new FileApi("greeting.txt"); 
    if(fileapi.exists()) 
    { 
     System.out.println("File exists!"); 
     fileapi.writeFile("Putrajaya"); 
    } 
    System.out.println(fileapi.readFile()); 
    fileapi.close(); 
} 

}它爲什麼有3個錯誤?我做了什麼錯誤?

輸出:

FileApi.java:11:錯誤:預期 類公共FileApi(String s)將拋出異常 FileApi.java:11:錯誤:無效方法聲明;返回類型需要 類公共FileApi(String s)將拋出異常 FileApi.java:68:錯誤:文件的最終達成而解析}

+0

作爲除了下面的答案,將構造函數中的變量名稱pw更改爲pr – user

+1

我可以感受到編譯器並且無法解析代碼。 'super(s)'應該只在你的構造函數中被調用,而不是在方法中('readFile()')'createFile()'是另一個失敗,... –

回答

0

一個構造函數不應該包含class關鍵字。

變化

class public FileApi (String s) throws Exception 
{ 
    super(s); 
    pw = new PrintWriter(fw = new FileWriter(s, true)); 

} 

public FileApi (String s) throws Exception 
{ 
    super(s); 
    pr = new PrintWriter(fw = new FileWriter(s, true)); 

} 
+0

即時通訊仍然會出現同樣的錯誤 –

2

您有構造函數的語法錯誤。它應該是這樣的:

public FileApi (String s) throws Exception { 
    super(s); 
    pw = new PrintWriter(fw = new FileWriter(s, true)); 
} 

(在這一點上的class關鍵字是不正確的,這是混淆瞭解析器,以至於它不能給的你做了什麼錯一個體面的解釋)


雖然我們正在談論錯誤,但將方法或構造函數聲明爲拋出Exception是一個重大錯誤。如果某些事情被宣佈爲「拋出你所想象的任何異常」,那麼它就很難做到理性的異常處理。

這:

pw = new PrintWriter(fw = new FileWriter(s, true)); 

只是gratiutous,IMO。這是更可讀的,如果你把它寫成兩個語句:

fw = new FileWriter(s, true); 
    pw = new PrintWriter(fw); 

最後,聲明該PrintWriter爲:

PrintWriter pr; 

時,它應該是:

PrintWriter pw; 
+0

即時仍然得到相同的錯誤 –

+0

我不相信你。你應該會得到不同的編譯錯誤。嘗試並自己修復它們:您將更多地瞭解這一點。 –

+0

即時對不起,我發現它,但即時通訊仍然得到同樣的錯誤,謝謝btw :) –

相關問題