I have a coin flip project for java. the coin flip and count work fine, but we a
ID: 3703408 • Letter: I
Question
I have a coin flip project for java. the coin flip and count work fine, but we are also supposed to have a seperate function (flip) that returns true for heads and false for tails on each toss. Haven't been able to get that to work. Also, it is unclear whether or not the assignment requires an image of a coin to display heads or tails with each toss. Just in case, help with that would also be appreciated. Here is the code I have...Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Coin Toss Simulation</title>
<script type = "text/javascript">
<!--
var heads = 0;
var tails = 0;
function toss()
{
var headsField = document.getElementById( "heads" );
var tailsField = document.getElementById( "tails" );
if ( coin() )
{
++heads;
headsField.value = heads;
}
else
{
++tails;
tailsField.value = tails;
}
}
function coin()
{
return Math.floor( Math.random() * 2 ) == 1
}
function flip()
{
return (Math.floor(Math.random() * 2) == 0);
}
//-->
</script>
</head>
<body>
<h1>Coin Toss Simulation</h1>
<form action = "">
<table border = "2">
<tr><td>Heads</td>
<td><input id = "heads" type = "text" />
</td>
</tr>
<tr><td>Tails</td>
<td><input id = "tails" type = "text" />
</td>
</tr>
<tr><td><input type = "button" value = "Toss Coin"
onclick = "toss()" /></td>
<td><input id = "tails" = "false" /></td>
</tr>
</table>
</form>
</body>
</html>
Explanation / Answer
Answer.)
Code : Updated some styles and look also.
<!DOCTYPE html>
<html>
<head>
<title>Coin Toss Simulation</title>
<script type = "text/javascript">
<!--
var heads = 0;
var tails = 0;
function toss()
{
var headsField = document.getElementById( "heads" );
var tailsField = document.getElementById( "tails" );
var result = document.getElementById('result');
if ( coin() )
{
++heads;
headsField.value = heads;
flip('True','green');
}
else
{
++tails;
tailsField.value = tails;
flip('False','red');
}
}
function coin()
{
return Math.floor( Math.random() * 2 ) == 1
}
function flip(res,col)
{
result.value=res;
result.style.color=col;
}
//-->
</script>
</head>
<body>
<h1>Coin Toss Simulation</h1>
<form action = "">
<table border = "2">
<tr><td>Heads</td>
<td><input id = "heads" type = "text" disabled/>
</td>
</tr>
<tr><td>Tails</td>
<td><input id = "tails" type = "text" disabled/>
</td>
</tr>
<tr><td><input type = "button" value = "Toss Coin"
/></td>
<td><input id = "result" type="text" disabled/></td>
</tr>
</table>
</form>
</body>
</html>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.