TransWikia.com

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

Stack Overflow Asked by Dan _ on November 24, 2021

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

One Answer

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.

Answered by p4czyk on November 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP