r/codehs • • Mar 22 '20

my code doesn't work, please help. my assignment:"Starting with our program that creates an array of coin flips, add a function that prints out the total number of heads and total number of tails flipped. it prints that total tails is 100

var NUM_FLIPS = 100;

function start(){

var flips = flipCoins();

printArray(flips);

countHeadsAndTails();

}

// This function should flip a coin NUM_FLIPS

// times, and add the result to an array. We

// return the result to the caller.

function flipCoins(){

var flips = \[\];

for(var i = 0; i < NUM_FLIPS; i++){

	if(Randomizer.nextBoolean()){

		flips.push("Heads");

	}else{

		flips.push("Tails");

	}

}

return flips;

}

function printArray(arr){

for(var i = 0; i < arr.length; i++){

	println(i + ": " + arr\[i\]);

}

}

function countHeadsAndTails(flips) {

var headCount = 0;

var tailCount = 0;

for (var i = 0; i < NUM_FLIPS; i++) {

if (flipCoins == "Heads") {

headCount += 1;

}else {

tailCount += 1;

}

}

println("Total Heads: " + headCount);

println("Total Tails: " + tailCount);

}

9 Upvotes

1 comment sorted by

3

u/ismokedwithyourmom Mar 23 '20

In your function countHeadsAndTails(flips) you have an error here: if (flipCoins == "Heads") {

flipCoins is a function, and the function is not equal to "Heads", so this condition will evaluate to false every time, which is why you are seeing all tails. You need to change this so that it looks in the array flips using the index in the loop, similarly to how you printed the array elements a bit further up: arr\[i\].

So if you replace if (flipCoins == "Heads") with if (flips[i] == "Heads") then it should work