简体   繁体   中英

Recursive function failing with “This method must return a result of type int”

This code is supposed to do x/y , but for some reason, it says:

This method must return a result of type int

Can you help me fix it?

public class Recursion2 {

    public static void main(String[] args) {

        System.out.println(func3(4, 2));
        
    }//main

    public static int func3(int x, int y)
    {
    if(x == y) return 1;
    if(x - y < x) return 1 + func3(x - y, y);
    } 
}//class

Change this:

if(x - y < x) return 1 + func3(x - y, y);

To:

if((x - y) < x) return 1 + func3(x - y, y);

Addition:

Maybe the problem causes because not every time a result is returned. In Java you have to return a result always. So you have to add else-cases or a default case. This would fix the issue I think.

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