Question

In: Computer Science

Create a program named DiceGame.Java (in Java lagnuage of course) The problem/background info: Suppose someone comes...

Create a program named DiceGame.Java (in Java lagnuage of course)

The problem/background info: Suppose someone comes to you and says “I have a 6-sided Die and different one that has 4 sides. Both are fair dice. I would like to propose a game. We will roll both dice and I will give you $3.00 if the total is less than 5 and $8.00 if the total is exactly equal to 5. But if the total is greater than 5, you give me $2.00.”   Should you do it? Should you do it if the second die had 6 sides?


Your program will simulate this:   You are given a class called Die, which has a default constructor (makes it 6-sided) and has a parameterized constructor that accepts a number of sides (minimum 4 sides or else it will throw an exception).   It also has a method called roll() which rolls itself and returns the (int) result; it also has a method called getNumSides() which returns the (int) number of sides it has.   You will write a program called DiceGame.java that simulates running the game over and over by doing the following:

  • Ask the user how many sides the second die should have; store the response.
  • Ask the user how many times to roll the dice; store the response.
  • Ask the user how often to print the results; store the response.
  • Ask the user to enter their name and store the response. Their name can have spaces in it.
  • Create a 6-sided die to use.
  • Create a die with as many sides as the user entered (using its parameterized constructor) to use.
  • Skip a line (use \n in your next output to do this) and then print “Experiment by: “ and then their name.   But…if their name has more than 5 characters, then just print first 5 characters of the name; otherwise print the whole name.
  • Tell both dice to roll themselves as many times as the user said to. As this is happening,
    • At every roll, add up the dice results, calculate the “winnings,” and keep track of how much money you have won or lost since the game began. The money should look like money (see below for how to do this).
    • Every n rolls, print the number of rolls that have occurred so far and the average money won/lost (total divided by number of rolls so far). n here is how often the user said to print the results. See the example below for the exact format.
  • After all the rolls are finished, print the final number of rolls and the average money won/lost (total divided by number of rolls).

Notes:

  • Don’t forget to flush the extra ENTER from the input stream (the program has .nextInt followed by .nextLine). For maintainability, that statement deserves a comment to explain why it is there.
  • Be sure that your output lines contain the exact wording; otherwise the tester will not pick up the line.
  • There should be a tab before the words “Average winning per roll:”
  • When looping n times, programmers generally use a for loop where i starts at 0 and keeps going while i
  • To make a result look like money, create an instance of the NumberFormat class, like this:

NumberFormat money = NumberFormat.getCurrencyInstance();

                ( you will have to import java.text.NumberFormat; )

            Then use your instance whenever you print your_calculation, like this

                                System.out.println(money.format(your_calculation));

                When formatted, negative money will be in parentheses rather than having a minus sign.

// This class will simulate a Die (half a pair of dice)

public class Die

{

//------- data

private int numSides;

private java.util.Random rGen;

//------- constructors

public Die()

{

this(6); //call parameterized constructor, as if 6 were passed in

}

public Die(int theSides)

{

if (theSides < 4)

throw new IllegalArgumentException("A Die cannot have less than 4

sides");

numSides = theSides;

rGen = new java.util.Random(numSides);

}

//------- methods

//getNumSides - returns the number of sides

public int getNumSides()

{

return numSides;

}

//roll - returns a random number from 1-numSides. The seed for the

random number generator should be the numSides

// (so everyone's results are the same...)

public int roll()

{

return rGen.nextInt(numSides) + 1;

}

}

Example1:

How many sides should the second die have?

4

How many times should we roll the dice?

87654

How often should we print results?

10000

What is your name?

Stephanie

Experiment by: Steph

Rolls: 10000    Average winning per roll: $0.90

Rolls: 20000    Average winning per roll: $0.91

Rolls: 30000    Average winning per roll: $0.92

Rolls: 40000    Average winning per roll: $0.91

Rolls: 50000    Average winning per roll: $0.92

Rolls: 60000    Average winning per roll: $0.91

Rolls: 70000    Average winning per roll: $0.91

Rolls: 80000    Average winning per roll: $0.91

Rolls: 87654    Average winning per roll: $0.91

Example2:

How many sides should the second die have?

6

How many times should we roll the dice?

400

How often should we print results?

100

What is your name?

Joe

Experiment by: Joe

Rolls: 100      Average winning per roll: ($0.45)

Rolls: 200      Average winning per roll: ($0.30)

Rolls: 300      Average winning per roll: ($0.37)

Rolls: 400      Average winning per roll: ($0.33)

Rolls: 400      Average winning per roll: ($0.33)

Solutions

Expert Solution

Program

import java.text.NumberFormat;
import java.util.Scanner;

class Die {
//------- data
   private int numSides;
   private java.util.Random rGen;
//------- constructors

   public Die() {
       this(6); // call parameterized constructor, as if 6 were passed in
   }

   public Die(int theSides) {
       if (theSides < 4)
           throw new IllegalArgumentException("A Die cannot have less than 4sides");

       numSides = theSides;

       rGen = new java.util.Random(theSides);
   }

//------- methods
//getNumSides - returns the number of sides
   public int getNumSides() {
       return numSides;
   }

//roll - returns a random number from 1-numSides. The seed for the
//random number generator should be the numSides
// (so everyone's results are the same...)
   public int roll() {
       return rGen.nextInt(numSides) + 1;
   }
}

public class DiceGambleSimulation {
   public static void main(String[] args) {
       // for taking console input
       Scanner sc = new Scanner(System.in);
       // for changing value to currency
      

       Die sixSided = new Die();// permenant die for all game

       // taking user input
       System.out.println("How many sides should the second die have?");
       int sides = sc.nextInt();
       System.out.println("How many times should we roll the dice?");
       int roll = sc.nextInt();
       System.out.println("How often should we print results?");
       int resultPrint = sc.nextInt();
       sc.nextLine();
       System.out.println("What is your name?");
       String name = sc.nextLine();
      
//       int sides = 4;
//       int roll = 87654;
//       int resultPrint=10000;
//       String name="Stephanie";
      
       Die customeSide = new Die(sides);// custome die by user

       double moneyCal = 0, avg;
       int totalRun = 0, rollCal;
       int newTotal = roll / resultPrint;//calcualting how many time the main loop will run
       double[] ar = new double[newTotal];
       int count =0;
      
       System.out.println("Experimented by: " + name);

       while (newTotal > 0) {// main loop
           for (int i = 0; i < resultPrint; i++) {// loop for calcuating money
               // getting roll value
               rollCal = sixSided.roll() + customeSide.roll();
               // chaing how much won or lost and adding it to moneyCal
               if (rollCal < 5)
                   moneyCal += 3;
               else if (rollCal == 5)
                   moneyCal += 8;
               else
                   moneyCal += -2;
           }
          
           totalRun += resultPrint;// total times the roll happened

           // money calculation
           avg = moneyCal / resultPrint;
          
           //putting it inside array for overall average
           ar[count] = avg; count++;
          
           printResult(totalRun, avg);

           moneyCal = 0;
          
           newTotal--;

       }
       //calculating the average of all money
       for(int i=0; i<ar.length; i++) {
           moneyCal+=ar[i];
       }
       avg = moneyCal / ar.length;
      
       printResult(roll, avg);

       sc.close();
   }
  
   //for printing the formated results
   public static void printResult(int rolls, double avg) {
       NumberFormat money = NumberFormat.getCurrencyInstance();
       System.out.print("Rolls: " + rolls + " Average winning per roll: ");
       if (avg >= 0)
           System.out.println(money.format(avg));
       else {// when amount is negetive
           avg = Math.abs(avg);
           System.out.println("(" + money.format(avg) + ")");
       }
   }
}

Output


Related Solutions

Use the below info to create a java program A GUI interface to ensure a user...
Use the below info to create a java program A GUI interface to ensure a user is old enough to play a game. Properly formatted prompts to input name, address, phone number, and age. Remember that name, address, phone number, etc. can be broken out in additional fields. Refer to the tutorial from this week’s Reading Assignment Multiple vs. Single Field Capture for Phone Number Form Input for help with this. Instructions to ensure that the information is displayed back...
Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
Java Programming Create a class named Problem1, and create a main method, the program does the...
Java Programming Create a class named Problem1, and create a main method, the program does the following: - Prompt the user to enter a String named str. - Prompt the user to enter a character named ch. - The program finds the index of the first occurrence of the character ch in str and print it in the format shown below. - If the character ch is found in more than one index in the String str, the program prints...
Create a program in JAVA that displays a design or picture for someone in your quarantine...
Create a program in JAVA that displays a design or picture for someone in your quarantine household/group: a pet, a parent, a sibling, a friend. Make them a picture using the tools in TurtleGraphics and run your program to share it with them! Use a pen object, as well as any of the shape class objects to help you create your design. You must use and draw at least 5 shape objects. - You must use a minimum of 4...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a package named threeDimensional and put all 3 of the classes discussed below in this package Include a header comment to EACH OF your files, as indicated in your instructions. Here's a link describing the header. Note that headers are not meant to be in Javadoc format. Note that Javadoc is a huge part of your grade for this assignment. Javadoc requires that every class,...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a package named threeDimensional and put all 3 of the classes discussed below in this package Include a header comment to EACH OF your files, as indicated in your instructions. Here's a link describing the header. Note that headers are not meant to be in Javadoc format. Note that Javadoc is a huge part of your grade for this assignment. Javadoc requires that every class,...
write program in java Create a class named PersonalDetails with the fields name and address. The...
write program in java Create a class named PersonalDetails with the fields name and address. The class should have a parameterized constructor and get method for each field.  Create a class named Student with the fields ID, PersonalDetails object, major and GPA. The class should have a parameterized constructor and get method for each field. Create an application/class named StudentApp that declare Student object. Prompts (GUI input) the user for student details including ID, name, address, major and GPA....
Create a new Java program named AllAboutMe (For JAVA we use blue J) Write code to...
Create a new Java program named AllAboutMe (For JAVA we use blue J) Write code to have the program print your name, favorite color, and three hobbies to a new text file called “AllAboutMe” using PrintStream. Submit code.
In java: -Create a class named Animal
In java: -Create a class named Animal
Java program Create a constructor for a class named Signal that will hold digitized acceleration data....
Java program Create a constructor for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp data The constructor...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT