[英]Can't seem to figure out why my loop wont progress
我似乎无法弄清楚为什么我的 for 循环不起作用。 我已经上了大约一个小时了,我最近的一次是这个。 我想知道你可以用 6、9 和 20 包购买多少个 McNugget。 我需要 dopeChecker(x) 做的就是返回一个真或假。 我还没有实施检查下一个号码,因为它甚至不会发现可以购买 6 包。 我知道它在某个地方的循环中,但我就是不知道在哪里。 这是麻省理工学院开放课件问题 2 的形式。我不知道你们是否看过,但我只是让你们知道这是我获取信息的地方。
int x = 0, y = 0, z = 0;// These will the the pack of McNuggets that we can buy.
int testFor = 0; //This will be the number of McNuggets we are looking for.
int matches = 0; //This will be the number of consecutive matches we will be looking for.
public void dopeEquation(){
while (matches < 6){//It's 6 Because that is the smallest order of nuggets we can buy.
//Looking for smaller nuggets then we can buy would not make sense.
while (testFor < 6){
testFor++;
}
if (dopeChecker(testFor)){
matches++;
} else{
matches = 0;
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
}
}
}
private boolean dopeChecker(int testFor){
for ( x = 0 ; x*6 <= testFor; x++){
for ( y = 0 ; y*9 <= testFor; y++){
for (z = 0 ; z*20 <= testFor;){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}
}
}
return false;
}
}
z 变量始终为 0,您无需更改它。
以下是最里面的 for 循环。 我已经评论了问题出在哪里。 如您所见, z
永远不会被实现。 因此,循环永远不会终止,因为 0 <= testFor,因为 TestFor >= 6。
for (z = 0 ; z*20 <= testFor;/* incrementor needed here*/){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}
您的代码进入第一个 while 循环:
while (matches < 6){
然后使用以下代码将 testFor 增加到 6:
while (testFor < 6){
testFor++;
}
然后去dopeChecker:
dopeChecker(int testFor)
然后进入第三个循环,对于 z:
for (z = 0 ; z*20 <= testFor;) {
...
}
z 永远不会增加,因此您需要将其写为:
for (z = 0 ; z*20 <= testFor; z++){
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.