2016-07-13 68 views
-3

下面的代碼來自this答案「不能返回爲void結果類型的值」的錯誤

try { 
     // get all the interfaces 
     List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); 
     //find network interface wlan0 
     for (NetworkInterface networkInterface : all) { 
      if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue; 
     //get the hardware address (MAC) of the interface  
      byte[] macBytes = networkInterface.getHardwareAddress(); 
      if (macBytes == null) { 
       return ""; 
      } 


      StringBuilder res1 = new StringBuilder(); 
      for (byte b : macBytes) { 
       //gets the last byte of b 
       res1.append(Integer.toHexString(b & 0xFF) + ":"); 
      } 

      if (res1.length() > 0) { 
       res1.deleteCharAt(res1.length() - 1); 
      } 
      return res1.toString(); 
     } 
    } catch (Exception ex) { 
      ex.printStackTrace(); 
    } 

我得到的那些2線錯誤Cannot return a value with void result typereturn "";return res1.toString();我把裏面的代碼public void onStart()我該如何解決這個,你能告訴我這個問題的原因嗎?

+0

那麼如果try塊引發異常會發生什麼?那個回報在哪裏? – SoroushA

+0

我的猜測是,你有一個void方法內的代碼,並且void方法不返回任何東西 –

回答

1

您需要更改線路

public void onStart() 

public String onStart() 

這是因爲你正在返回一個字符串,而一個void函數不會返回任何數據。

如果該方法不能被改變爲一個字符串返回類型,那麼你可以只是把串入您之前在節目中宣佈,然後使用

return; 

要退出方法的變量。

+0

不可以,因爲這是覆蓋Android活動的生命週期方法。 – Vucko

+0

謝謝!我有一個相關的問題。當我做以下。 'macText =(TextView)findViewById(R.id.MACaddress); macText.setText(macBytes);'我得到'錯誤:找不到適合setText的方法(byte [])'我該如何解決這個問題? – Dake

+0

你應該爲此創建一個新問題。因爲它與這個問題無關。我可以在那裏回答。 – Darren

2

,而不是返回一個空字符串,只是return;

中的方法都是無效並不返回任何東西,但你可以用return語句終止的操作如果某些條件不符合!

我希望這有助於!

+0

謝謝!我有一個相關的問題。當我做以下。 'macText =(TextView)findViewById(R.id.MACaddress); macText.setText(macBytes);'我得到'錯誤:找不到適合setText的方法(byte [])'我該如何解決這個問題? – Dake

+0

setText(String value)接受一個字符串,而不是byte []數組。只要通過一個字符串 – Eenvincible

+0

你是什麼意思?我們如何做到這一點? – Dake

0

問題很明顯,您正在返回函數public void onStart()的值。你聲明返回類型爲void,但你有返回語句。

嘗試不同的方式返回值,就像把它放在請求/會話或靜態變量(不建議報告)等

相關問題