user3349993
user3349993

Reputation: 309

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

Upvotes: 1

Views: 60

Answers (3)

NPE
NPE

Reputation: 500307

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.

Upvotes: 6

Just

return isThree();

in the else should do it.

Upvotes: 3

tddmonkey
tddmonkey

Reputation: 21184

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

isThree();

to

return isThree();

Upvotes: 4

Related Questions