【问题标题】:"Cannot return a value with void result type" error“无法返回结果类型为 void 的值”错误
【发布时间】:2016-07-13 20:03:37
【问题描述】:

以下代码来自this答案

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();
    }

我在这两行出现错误Cannot return a value with void result typereturn "";return res1.toString(); 我将代码放入public void onStart() 如何解决这个问题,你能告诉我这个问题的原因吗?

【问题讨论】:

  • 如果 try 块抛出异常会发生什么?回报在哪里?
  • 我的猜测是,你在 void 方法中有该代码,而 void 方法不返回任何内容

标签: java android android-studio


【解决方案1】:

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

无效的方法不返回任何内容,但如果不满足某些条件,您可以使用 return 语句终止操作!

我希望这会有所帮助!

【讨论】:

  • 谢谢!我有一个相关的问题。当我执行以下操作时。 macText = (TextView) findViewById(R.id.MACaddress); macText.setText(macBytes); 我收到 error: no suitable method found for setText(byte[]) 我该如何解决这个问题?
  • setText(String value) 采用字符串,而不是 byte[] 数组。只需传递一个字符串
  • 什么意思?我们该怎么做?
  • 这就是我的意思developer.android.com/reference/android/widget/TextView.html;有一些方法可以在 TextView 组件上设置文本 - setText(int resId), setText(char[] text, int start, int len) , setText(CharSequence text, TextView.BufferType type), setText(CharSequence text)
  • 我想向用户显示macBytes,如何显示?
【解决方案2】:

你需要换行

public void onStart()

public String onStart()

这是因为您返回的是字符串,而 void 函数不返回任何数据。

如果方法无法更改为 String 返回类型,那么您可以将字符串放入您在程序前面声明的变量中,然后使用

return;

退出方法。

【讨论】:

  • 不,你不能,因为它是被覆盖的 Android 活动的生命周期方法。
  • 谢谢!我有一个相关的问题。当我执行以下操作时。 macText = (TextView) findViewById(R.id.MACaddress); macText.setText(macBytes); 我收到 error: no suitable method found for setText(byte[]) 我该如何解决这个问题?
  • 您应该为此创建一个新问题。因为它与这个问题无关。我可以在那里回答。
【解决方案3】:

问题很明确,您正在为函数 public void onStart() 返回一个值。您将返回类型声明为 void,但您有返回语句。

尝试不同的方式来返回值,比如把它放在请求/会话或静态变量(不推荐)等

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 2014-04-23
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多