首页 > 解决方案 > 为什么我不能在 Java 代码中使用“return”?

问题描述

我在第四行的 Java 代码有问题。我有这个错误:“此方法必须返回 int 类型的结果”。所以我没有返回'c'。我怎样才能回来?

public class bese_bolunme {

static int function(int b) 
{

    for (int c=0;c<b;c++) 
    {

        if(c%5==0) 
        {
            System.out.println(c);
            return c;
        }



    }
}

public static void main(String[] args) {
    function(36);
}

标签: javareturn

解决方案


由于您在函数签名中声明它返回一个整数,因此您必须在函数的所有执行流程中返回一个整数。

static int function(int b) 
{

   for (int c=0;c<b;c++) 
   {

    if(c%5==0) 
    {
        System.out.println(c);
        return c;
    }
} //end for loop
 return -1;     //Or other logic you prefer
}

推荐阅读