简体   繁体   中英

Have to specify return in method, but I want the method to call itself again instead of returning

I have written a method. It is imitating flipping a coin and trying to detect a case "three heads in a row". As soon as three heads in a row appears (counter=3), the method returns number of iterations it took to get to this point (genCounter).

The problem is that eclipse says that this method should return "int", but I did return genCounter.(both counter and genCounter are int instance variables). As I understood from browsing the internet, the problem is that I am not returning anything in else. But I don't want it to return anything, in case of else I want to start my method from the beginning.

private int isThree(){
    String coin = rg.nextBoolean()?"Heads":"Tails";
    if (coin.equals("Heads")){
        counter += 1;
    }else{
        counter = 0;
    }
    genCounter += 1;
    if (counter == 3) {
        return genCounter;
    }else{
        isThree();
    }
}

But I don't want it to return anything, in case of else I want to start my method from the beginning.

Hint: to repeat some actions, use a loop (which will also solve your current problem).

You are currently using recursion for this; while doable, it does complicate things unnecessarily.

You need to tell the method to return the value of the call to itself. Change:

isThree();

to

return isThree();

Just

return isThree();

in the else should do it.

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