Guest User

Untitled

a guest
Nov 23rd, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. //purpose simultest the tossing of a coin using math.random(). We will have Math.Random(); generate a 1 or a 2 to stand for heads or tails.
  2. import java.util.Scanner;
  3. public class CoinFlip {
  4.  
  5. public static void main(String[] args) {
  6. Scanner input = new Scanner(System.in);
  7.  
  8. //explain
  9. System.out.println("This program will simulate the flipping of a coin.");
  10. System.out.print("How many tosses do you want to simulate.");
  11. long numTosses = input.nextLong();
  12.  
  13. //create accumulators to hold results
  14. long numHeads = 0;
  15. long numTails = 0;
  16.  
  17. // loop for however many times the user inputed.
  18.  
  19. for(long i = 1; i <= numTosses; i++) {
  20. int tossResult = (int)(Math.random() * 2 + 1);
  21.  
  22. //assign to appropriate accumulator
  23. if(tossResult == 1) {
  24. numHeads++;
  25. }else if(tossResult == 2) {
  26. numTails++;
  27. }else {
  28. System.out.println("Error.");
  29. }
  30. }
  31. System.out.println("\nNum Tosses: " + numTosses);
  32. System.out.println("\nNum Tosses that were heads: " + numHeads);
  33. System.out.println("\nNum Tosses that were tails: " + numTails);
  34.  
  35. //work the percentages of each
  36. double percentHeads = 0.0;
  37. double percentTails = 0.0;
  38. percentHeads = (double)numHeads / numTosses * 100;
  39. percentTails = (double)numTails / numTosses * 100;
  40.  
  41. System.out.println("\nPercentage of heads was: " + percentHeads + "%");
  42. System.out.println("\nPercentage of tails was: " + percentTails + "%");
  43.  
  44. }
  45.  
  46. }
Add Comment
Please, Sign In to add comment