简体   繁体   English

必须在方法中指定return,但是我希望方法再次调用自身而不是返回

[英]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.

相关问题 使用PowerMockito模拟私有方法调用返回null而不是返回List <String> :(不想执行私有方法) - Mocking private method call using PowerMockito returns null instead of returning List<String>: (Want not to execute private method) 返回toString方法,不返回我想要的东西(Java) - Return toString method, not returning what I want (Java) 方法可以在捕获异常后再次调用自身吗? - Is it ok for a method to call itself again after catching an exception? 在我的实现中,我希望该方法具有不同的返回类型 - In my implementation I want to have different return type of the method 单击按钮后如何在JSON中获取ID并想在post方法中再次发送该ID - How i have to get the id in JSON after click the button and want to send that id again in post method 我有一个方法,我想向我的主方法返回三个不同的值 - I have a method and I want to return three different values to my main method 为什么必须在Java中指定方法返回类型? - Why do you have to specify method return type in Java? Mocking 方法中的依赖项而不是方法本身 - Mocking a dependencies in a method instead of the method itself 我试图调用的方法不是返回值 - The method I am trying to call is not returning a value 在方法本身中使用方法返回值 - Usage of method return value in method itself
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM