2013-07-26 31 views
-3

我正在做一個小型的Java遊戲,並在編譯時我得到了一個錯誤:java無效的方法聲明;返回初始化科目編號類型,運行

error:invalid method declaration;return type requied 
public init() throws Exception { 
    ^

第一個版本是公共無效的init,但我不能做這樣的,因爲我需要使用try {..} catch(Malformed ...)或編譯時我得到了另一個錯誤(需要抓住等等等等)。

這是代碼:

public void run() throws Exception{ 
try{ 
this.zz(); 
}catch(MalformedURLException me){ 
throw me; 
} 
this.zo(); 
} 
+0

公共無效的init()拋出異常 –

+2

公衆詮釋init()拋出異常。添加返回類型。 – Veera

回答

0
error:invalid method declaration;return type requied 
public init() throws Exception { 
    ^
// You are missing the return type 

你忘了返回類型添加到方法聲明。每個Java方法都應該指定一個返回類型。如果它不返回任何內容給調用者,請將其設爲void。在你的情況下,它返回一個原始的int,所以聲明int作爲返回類型。

需要重新因子代碼一點:

// return type is int as you are returning primitive int `0`. 
public int init() throws MalformedURLException { 
    //... 
    try{ 
    this.zx(); 
    }catch(MalformedURLException me){ 
    // log the Exception here 
    // me.printStackTrace(); 
    // logger.error(... exception message ....); 
    throw me; 
    // in case you return 0 , in spite of the Exception 
    // you will never know about the exceptional situation 
    } 
    return 0; 
} 

參考JLS 8.4

+0

是的,但我不能使用void因爲MalformedURLException是需要的或URL不起作用。 – user2622574

+0

@ user2622574我沒有得到你。請多解釋一下。 – NINCOMPOOP

+0

如果我使用void,我不能使用return。我需要使用try {...}捕獲MalformedURLException,因爲this.zx具有URL(文件...)。 try..catch格式錯誤的需求返回 – user2622574

0

返回類型是強制性的。你必須提供一個。我想,沒有逃脫。

2

你忘了添加返回類型。既然你返回0,我假設你想返回一個int。因此,將您的標題更改爲:

public int init() throws MalformedURLException 

沒有理由擁有throws Exception。要儘可能具體。

一般來說,方法的語法是:

訪問修飾符公衆,保護私人返回類型原始,對象,無效方法名

這是關於Defining Methods的Oracle教程。

而且,不知道這是否適用,但如果你只打算返回僅0或1,例如,考慮改變你的方法頭:

public boolean init() throws MalformedURLException