[英]Break Iteration of Java loop with control flow with a recursive method
我通过尝试解决猴子/椰子/水手问题进行递归的尝试。
我在for循环停止方面遇到问题。 它只是迭代,但不确定我哪里出错了。
在我的3个测试用例中,方法testCoconuts返回我想要的值,但是,即使真实值是通过循环发送的,我的循环也会迭代到最后一个数字。
我确定它是我的布尔值,但我还无法弄清楚我在做什么错。
public class Test {
public static boolean testCoconuts(int s, int sr, int c){
if (c % s == 1 && sr > 0) {
Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
}
else if (c % s != 1) {
return false;
}
else if (sr == 0) {
System.out.println("solved");
return true; //returns true in all 3 test cases below
}
return false;
}
public static void main(String[] args) {
//int s and sr must me entered into the test program
//as the same number, ex s= 2, sr = 2
int sailors = 3;
Test.testCoconuts(2, 2, 7); //will print solved
Test.testCoconuts(3, 3, 79); //will print solved
Test.testCoconuts(4,4,1021); //will print solved
for (int testNuts = 1; testNuts < 100; testNuts++) {
if (Test.testCoconuts(sailors, sailors, testNuts)==true) {
System.out.println("solved!");
break;
}
else {
System.out.println(testNuts);
System.out.println("next iteration");
System.out.println(testNuts);
}
}
}
}
for循环将一直运行,直到testCoconouts
方法等于true为止。
现在,如果您看一下该方法,可能会有四种结果:
if (c % s == 1 && sr > 0)
else if (c % s != 1)
else if (sr == 0)
但是,只有在它们的后三个中,您才明确说明该方法应返回的值。
所以-在第一个结果中,由于没有其他说明,该方法将始终返回if语句外部所述的false。 我假设您想从递归本身返回结果,对吗?
尝试像这样更改第一个if语句,看看会发生什么:)
if (c % s == 1 && sr > 0) {
boolean result = Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
return result;
}
(可以在没有可变result
情况下以单线方式完成,但是为了清楚起见,我将其拆分了)
请记住,您以递归方式调用函数,并将返回值发送回上一个函数调用,而不是主函数
这是一个解决方案:
public class Test {
public static boolean testCoconuts(int s, int sr, int c){
boolean flag = false;
if (c % s == 1 && sr > 0){
flag = Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
}
else if (c % s != 1){
return flag;
}
else if (sr == 0){
System.out.println("solved");
return true; //returns true in all 3 test cases below
}
return flag;
}
public static void main(String[] args){
//int s and sr must me entered into the test program
//as the same number, ex s= 2, sr = 2
int sailors = 3;
//Test.testCoconuts(2, 2, 7); //will print solved
//Test.testCoconuts(3, 3, 79); //will print solved
//Test.testCoconuts(4,4,1021); //will print solved
for (int testNuts = 1; testNuts < 100; testNuts++){
boolean flag = Test.testCoconuts(sailors, sailors, testNuts);
System.out.println(testNuts);
if (flag==true){
System.out.println("solved!");
break;
}
else{
System.out.println(testNuts);
System.out.println("next iteration");
System.out.println(testNuts);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.