[英]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).
连续出现三个头时(counter = 3),该方法将返回达到此点所需的迭代次数(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). 问题在于eclipse表示此方法应返回“ int”,但我确实返回了genCounter。(counter和genCounter都是int实例变量)。 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. 在
else
应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.