Return类型方法"Return value of the method is never used"问题

Return type method "Return value of the method is never used" problem

我有一个任务要完成。我必须创建一个 return 类型的方法,将 String 数组作为参数并将 returns 转换为 int。所以我的方法工作得很好,我将用它来计算数组中一个元素的多个元素,但在方法名称上它说“Return 方法的值从未使用过”。我只是不明白我在方法上缺少什么。这是我的方法:

public static int countMultiple(String[] s){
    int counter = 0;
    for (int i = 0; i < s.length; i++) {
        s[i] = s[i].trim();
        if (s[i].contains(" ")) {
            counter++;
        }
    }
    System.out.println(counter);
    return counter;
}

我假设你的意思并不是真正的错误,而是来自你 IDE 的警告。你的 IDE 基本上想告诉你,你 return 一个值与你的方法(在你的例子中是一个 int 值),但永远不要使用这个值来处理它。

因此,IDE 建议您改进代码,就好像您永远不需要该值一样,您也可以 return 一个空值。因此你有两种方法可以解决这个问题:

a) 在调用 countMultiple(String[] s) 的方法中,您可以使用该值,例如通过简单地记录它。

b) 如果你不需要调用者方法中的值,你可以return void: public static void countMultiple(String[] s)

对于案例 b,考虑从方法中也删除 return counter;