首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我似乎不明白为什么我的循环不会继续

我似乎不明白为什么我的循环不会继续
EN

Stack Overflow用户
提问于 2011-07-20 13:35:50
回答 3查看 203关注 0票数 1

我似乎不明白为什么我的for循环不能工作。我已经在网上呆了大约一个小时了,离我最近的就是这个。我正在尝试找出使用6、9和20包可以买到多少McNuggets。我需要dopeChecker(x)做的就是返回true或false。我还没有实现检查下一个数字,因为它甚至不会发现6包还可以购买。我知道它在某个地方,但我就是找不到。这是麻省理工学院公开课的问题2,我不知道你们有没有看过,但我只是想让你们知道,这就是我获取信息的地方。

代码语言:javascript
复制
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;

}
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-20 13:52:32

您的代码放在第一个while循环中:

代码语言:javascript
复制
while (matches < 6){

然后使用以下代码将testFor增加到6:

代码语言:javascript
复制
 while (testFor < 6){
            testFor++;
        }

然后转到dopeChecker:

代码语言:javascript
复制
 dopeChecker(int testFor)

然后插入第三个循环,对于z:

代码语言:javascript
复制
 for (z = 0 ; z*20 <= testFor;) {
 ...
 }

Z永远不会递增,因此您需要将其写为:

代码语言:javascript
复制
 for (z = 0 ; z*20 <= testFor; z++){
}
票数 1
EN

Stack Overflow用户

发布于 2011-07-20 13:39:05

Z变量始终为0,您不能更改它。

票数 3
EN

Stack Overflow用户

发布于 2011-07-20 13:42:00

下面是最里面的for循环。我已经评论了问题所在。如您所见,z从未实现过。因此,从testFor >= 6开始,循环将永远不会终止,因为0 <= TestFor。

代码语言:javascript
复制
        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");
            }
        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6757426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档