让我的for循环工作的麻烦

use*_*613 1 java loops for-loop

我试图做一个抛硬币模拟器,但无论我做什么这个循环被跳过并返回0头和0尾.randNumgenerator之前已定义,但我不认为它与我的问题有任何关系.

注意:"不工作"在我运行时从不出现,所以我假设循环本身存在问题,而不是循环内部的问题.我还将循环退出条件设置为4,即使该程序完成时它将执行用户想要的任何数量的硬币抛出.

这是我的代码部分.谁能告诉我为什么我总是得到0头和0尾?

final int sidesOfCoin = 2;
int flipsDone = 0;
int heads = 0;
int tails = 0;
int randomCoinValue;

for (heads = 0 ; flipsDone == 4; flipsDone++){
    randomCoinValue = randNumGenerator.nextInt(sidesOfCoin);
    if(randomCoinValue == 0){
        heads++;
    }
    else if(randomCoinValue == 1){
        tails++;
    }
    else{
        System.out.println("not working");
    }
}

System.out.println(heads + " heads and " + tails + " tails means " + (((double)heads * 100)/flipsDone) + "% tosses were heads");
Run Code Online (Sandbox Code Playgroud)

Pet*_*hev 6

不应该flipsDone <= 4吗?否则,您将立即退出循环.

  • 哇.我显然不理解for循环是如何工作的.谢谢. (4认同)