简体   繁体   中英

Why I can't use “return” in my code at Java?

I have a problem with my Java Code at the fourth line. I have this error: "this method must return a result of type int". So I didn't return 'c'. How can I return?

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

Since you declared in your function signature that it returns an Integer, you must, in all execution flows of your function return an Integer.

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
}

On every execution path in the method function(int b) a return statement must be reached. You are taking care of not all paths: Ie what should the method return in case of not entering the for loop?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM