2016-07-13 51 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,但你有返回语句。

尝试不同的方式返回值,就像把它放在请求/会话或静态变量(不建议报告)等

相关问题