This is a JAVA program for an automatic coin toss; you enter the number of tosses you want to make and then the program does the tosses by itself, where it also checks to see if the result of the toss is heads or tails. This is from Chapter 5 of Tony Gaddis' Starting out with JAVA, 4th Edition.
Here's the program; a series of details follows onwards.
import javax.swing.JOptionPane;
import java.util.Random;
public class Chapter5CoinToss
{
public static void main(String[] args)
{
String input;
int numberOfTosses;
input =
JOptionPane.showInputDialog("How many times do you want this virtual coin to be tossed?");
numberOfTosses = Integer.parseInt(input);
coinToss(numberOfTosses);
JOptionPane.showMessageDialog(null, "Thank you and come again!");
}
public static void coinToss(int number)
{
int numberOfHeads = 0,
numberOfTails = 0,
currentNumber,
currentToss = 1;
Random tossMachine = new Random();
while (currentToss <= number)
{
currentNumber = tossMachine.nextInt(1 + 1);
if (currentNumber == 0)
numberOfHeads++;
else if (currentNumber != 0)
numberOfTails++;
currentToss++;
}
JOptionPane.showMessageDialog(null, "Out of the number of tosses you asked, there were " +
numberOfHeads + " heads resulted and " + numberOfTails + " tails.");
}
}
It is simply three JOptionPane windows where the first, you enter the number of tosses to execute. Then, through one of the Random class methods and a custom method named coinToss consisting of four integer variables, one Random object, a while loop, an if-else-if statement, and the JOptionPane's showMessageDialog method, the program executes the tosses and checks if the resulting toss is heads or tails.
There are no images used; it's all computer logic, in binary numbers. All of this invisible process happens within just less than 50 lines of code.
Well, I'll see you around!
Saturday 15 December 2012
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment