simulate a pair of dice.

Simulation.java 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. public class Simulation
  2. {
  3. Integer numberOfDice;
  4. Integer numberOfTosses;
  5. public Simulation(Integer numberOfDice,Integer numberOfTosses){
  6. this.numberOfDice = numberOfDice;
  7. this.numberOfTosses = numberOfTosses;
  8. }
  9. Bins results = new Bins();
  10. public void runSimulation(){
  11. int currentRoll = 0;
  12. Dice dice = new Dice(numberOfDice);
  13. Bins results = new Bins();
  14. while(currentRoll < numberOfTosses){
  15. int result = dice.tossSum();
  16. currentRoll++;
  17. results.increment(result);
  18. }
  19. printHeader();
  20. printResults(results);
  21. }
  22. public float ratioOfTosses(int numberOfSpecificResult){
  23. return numberOfSpecificResult/(float)numberOfTosses;
  24. }
  25. public void printHeader(){
  26. System.out.println("***\n" + "Simulation of " + numberOfDice
  27. + " dice tossed for " + numberOfTosses + " times.\n***");
  28. }
  29. public void printResults(Bins results){
  30. for(int i = 2; i <=12;i++){
  31. float ratio = ratioOfTosses(results.getN(i));
  32. StringBuilder stars = new StringBuilder();
  33. for(int j = 1; j < (ratio*100); j++){
  34. stars.append("*");
  35. }
  36. System.out.println(String.format("%2s :%9s:%5.2f ",i,results.getN(i),ratio)+stars.toString());
  37. }
  38. }
  39. }