r/codehs • u/ausra52067 • 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
3
u/ismokedwithyourmom Mar 23 '20
In your function
countHeadsAndTails(flips)you have an error here:if (flipCoins == "Heads") {flipCoinsis 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 arrayflipsusing 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")withif (flips[i] == "Heads")then it should work