似乎无法弄清楚为什么我的循环不会进展

时间:2011-07-20 05:35:50

标签: java

我似乎无法弄清楚为什么我的for循环不起作用。我现在已经待了大约一个小时了,我最接近的就是这个。我想知道你可以用6,9和20包购买多少个McNuggets。我需要dopeChecker(x)做的就是返回true或false。我还没有实现检查下一个号码,因为它甚至不会发现可以买到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;

}
}

3 个答案:

答案 0 :(得分:3)

z变量始终为0,您不会更改它。

答案 1 :(得分:1)

以下是最里面的for循环。我已经评论了问题所在。如您所见,z永远不会实现。因此,循环永远不会终止,因为0&lt; = testFor,因为TestFor&gt; = 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");
            }
        }

答案 2 :(得分:1)

你的代码进入第一个while循环:

while (matches < 6){

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

 while (testFor < 6){
            testFor++;
        }

然后去dopeChecker:

 dopeChecker(int testFor)

然后输入第3个循环,对于z:

 for (z = 0 ; z*20 <= testFor;) {
 ...
 }

z从不递增,因此您需要将其写为:

 for (z = 0 ; z*20 <= testFor; z++){
}