为什么我的Java“for”循环立即结束?

时间:2011-03-26 23:22:52

标签: java arrays loops

我的第一个循环似乎正确地构建了数组,当我在第二个“for”循环中打印出结果时,它会立即终止。我看不出错误。这是代码:

public class CoinFlip 
{
    private static int Flip()
    {
        return (int)(2*Math.random());   //returns 0 or 1; 0=Tails,1=Heads 
    }
    public static void main(String args[])
    {
        int HEADS = 1;
        int[] ConsecArray = new int[1000];   // the odds of ever having more than 1000 HEADS consecutively flipped are nil
        int Sequencecounter = 0;
        for (int i = 0; i < ConsecArray.length; i++)
        {
            if (Flip() == HEADS)
            {
                Sequencecounter++;
            }
            else    // we have a TAILS
            {
                // Check sequence counter, if > 0, logging to do...
                if (Sequencecounter > 0)
                {
                    // Update length counters
                    int index = Sequencecounter - 1; 
                    ConsecArray[index]++;
                    Sequencecounter = 0;
                }
                    // consecutive tails, continue in loop
            }
        }
        int j = ConsecArray.length;
        System.out.println("Length" + "     " + "NumberRunsOfHeads");
        for (int k = 0; k == j; k++)
        {
            int index = k + 1;
            String bucketName =  Integer.toString(index);
            String bucketValue = Integer.toString(ConsecArray[k]);
            System.out.println(bucketName + "     " + bucketValue);
        }
    }
}

6 个答案:

答案 0 :(得分:5)

第二次循环的第一次迭代:
k是0
j是1000
测试k == j失败
循环永远不会运行

答案 1 :(得分:2)

更改

for (int k = 0; k == j; k++)

for (int k = 0; k < j; k++)

答案 2 :(得分:1)

我认为您的意思是k <= jk < j,但您提出k == j。在第一次迭代期间不是这样,因此循环体永远不会执行。

    for (int k = 0; k == j; k++)
    {
        int index = k + 1;
        String bucketName =  Integer.toString(index);
        String bucketValue = Integer.toString(ConsecArray[k]);
        System.out.println(bucketName + "     " + bucketValue);
    }

答案 3 :(得分:1)

而不是for (int k = 0; k == j; k++)(相当于if (k == j))你想写或for (int k = 0; k < j; k++),即循环j次,而不是像k == j那样循环。

答案 4 :(得分:1)

此:

for (int k = 0; k == j; k++)

应该是这样的:

for (int k = 0; k < j; k++)

答案 5 :(得分:0)

kett_chup是对的。我想你想要“k&lt; j”。你在考虑“直到”而不是“为”。