Question

In: Computer Science

JAVA programming- answer prompts as apart of one java assignment Static static variables static methods constants...

JAVA programming- answer prompts as apart of one java assignment

Static

  • static variables
  • static methods
  • constants

Create a class Die representing a die to roll randomly.

☑ Give Die a public final static int FACES, representing how many faces all dice will have for this run of the program.

☑ In a static block, choose a value for FACES that is a randomly chosen from the options 4, 6, 8, 10, 12, and 20.

☑ Give Die an instance variable current, representing the last value it rolled. This cannot be less than 1 or more than FACES

☑ Give Die int instance variables maxCount and minCount. These cannot be negative.

☑ Give Die a method roll that randomly sets current to a value between 1 and FACES. If the die rolls a 1, increase minCount, if the die rolls FACES, increase maxCount.

☑ Give Die a static method sumDice, which takes a variable length parameter list of Dies and returns the sum of all their current values.

☑ Give Die a static method sameDice, which takes a variable length parameter list of Dies, and returns true only if all of them have the same current value. Do not compare the same two dice for equality twice while doing this.

☑ Give Die a static method differentDice, which takes a variable length parameter list of Dies, and returns true only if no two Dies have the same value. Do not compare the same two dice for equality twice while doing this.

☑ Give Die a static method findBest, which takes a variable length parameter list of Dies and returns the Die that has the best maxCount to minCount ratio (hint: does java think 1/2 > 1/4?).

☑ Give Die a static method dieStats which takes two ints, howMany and frequency. In the method, create howmany Dies, and roll them frequency times. At the end, report how often they rolled all the same, how often they rolled all different, the average of their sums, and the best die.

Solutions

Expert Solution

//********************************************************************
//  Dice.java       
//********************************************************************

class Die
{

// Note: If we changed the class definition to "public class Die"
// then we would put this class definition in a separate file Die.java

//  Represents one die (singular of dice) with faces showing values
//  between 1 and 6.

   private final int MAX = 6;  // maximum face value

   private int faceValue;  // current value showing on the die

   //-----------------------------------------------------------------
   //  Constructor: Sets the initial face value.
   //-----------------------------------------------------------------
   public Die()
   {
      faceValue = 1;
   }

   // Alternate Constructor

   public Die(int value)
   {
      faceValue = value;
   }

   //-----------------------------------------------------------------
   //  Rolls the die and returns the result.
   //-----------------------------------------------------------------
   public int roll()
   {
      faceValue = (int)(Math.random() * MAX) + 1;

      return faceValue;
   }

   //-----------------------------------------------------------------
   //  Face value mutator.
   //-----------------------------------------------------------------
   public void setFaceValue (int value)
   {
      faceValue = value;
   }

   //-----------------------------------------------------------------
   //  Face value accessor.
   //-----------------------------------------------------------------
   public int getFaceValue()
   {
      return faceValue;
   }

// Returns a string representation of this die. 
       public String toString() 
      { 
             String result = Integer.toString(faceValue); 
             return result; 
        } 

}

public class Dice
{

   //-----------------------------------------------------------------
   //  Creates two Die objects and rolls them several times.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Die die1, die2, die3;
      int sum;

      die1 = new Die();
      die2 = new Die();

      die1.roll();
      die2.roll();
      System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

// The previous two method calls are sloppy programming practice,
// as the method returns an int which is not "received"
// Better to do  this:

      int x = die1.roll();

// Or

      System.out.println("Die 1 " + die1.roll());

      die2.setFaceValue(4);
      System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

      sum = die1.getFaceValue() + die2.getFaceValue();
      System.out.println ("Sum: " + sum);

      sum = die1.roll() + die2.roll();
      System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
      System.out.println ("New sum: " + sum);

      die3 = new Die(4);
      System.out.println("Die Three : " + die3.getFaceValue());
  
      die3 = die2;
      System.out.println("Die Three : " + die3.getFaceValue());

// What happens if we change faceValue to public
// and then do die3.faceValue = 2; System.out.println("Die Two : " + die2.getFaceValue());


   }
}


public class PairOfDice {

    public int die1;   // Number showing on the first die.

    public int die2;   // Number showing on the second die.

   

    /**

     * Constructor creates a pair of dice and rolls them so that

     * they initially show some random value.

     */           

    public PairOfDice() {

        roll(); // Call the roll() method to roll the dice.

    }

   

    /**

     * Roll the dice by setting each die to be a random number between 1 and 6.

     */

    public void roll() {

        die1 = (int)(Math.random()*6) + 1;

        die2 = (int)(Math.random()*6) + 1;

    }

   

} // end class PairOfDice

The Modified PairOfDice Class

     /**

      * An object of class PairOfDice represents a pair of dice,

      * where each die shows a number between 1 and 6. The dice

      * can be rolled, which randomizes the numbers showing on the

      * dice.

      */

     public class PairOfDice {

    

        private int die1;   // Number showing on the first die.

        private int die2;   // Number showing on the second die.

        /**

         * Constructor creates a pair of dice and rolls them so that

         * they initially show some random value.

         */

        public PairOfDice() {

            roll(); // Call the roll() method to roll the dice.

        }

       

        /**

         * Roll the dice by setting each die to be a random number between 1 and 6.

         */

        public void roll() {

            die1 = (int)(Math.random()*6) + 1;

            die2 = (int)(Math.random()*6) + 1;

        }

               

        /**

         * Return the number showing on the first die.

         */

        public int getDie1() {

           return die1;

        }

       

        /**

         * Set the value of the first die. Throws an IllegalArgumentException

         * if the value is not in the range 1 to 6.

         */

        public void setDie1( int value ) {

           if ( value < 1 || value > 6 )

              throw new IllegalArgumentException("Illegal dice value " + value);

           die1 = value;

        }

       

        /**

         * Return the number showing on the second die.

         */

        public int getDie2() {

           return die2;

        }

       

        /**

         * Set the value of the second die. Throws an IllegalArgumentException

         * if the value is not in the range 1 to 6.

         */

        public void setDie2( int value ) {

           if ( value < 1 || value > 6 )

              throw new IllegalArgumentException("Illegal dice value " + value);

           die2 = value;

        }

       

        /**

         * Return the total showing on the two dice.

         */

        public int getTotal() {

           return die1 + die2;

        }

       

        /**

         * Return a String representation of a pair of dice, where die1

         * and die2 are instance variables containing the numbers that are

         * showing on the two dice.

         */

        public String toString() {

           if (die1 == die2)

              return "double " + die1;

           else

              return die1 + " and " + die2;

        }

       

     } // end class PairOfDice

    

    

    

The Main Program

     

     /**

      * Rolls a pair of dice until the dice come up snake eyes

      * (with a total value of 2). Counts and reports the

      * number of rolls.

      */

     public class RollFor2 {

    

        public static void main(String[] args) {

          

         PairOfDice dice; // A variable that will refer to the dice.

           int rollCount;    // Number of times the dice have been rolled.

    

           dice = new PairOfDice(); // Create the PairOfDice object.

           rollCount = 0;

           

           /* Roll the dice until they come up snake eyes. */

          

           do {

               dice.roll();

               System.out.println("The dice come up " + dice );

               rollCount++;

           } while (dice.getTotal() != 2);

          

           /* Report the number of rolls. */

          

           System.out.println("\nIt took " + rollCount + " rolls to get a 2.");

          

           /* Now, generate an exception. */

           

           System.out.println();

           System.out.println("This program will now crash with an error");

           System.out.println("when it tries to set the value of a die to 42.");

           System.out.println();

          

           dice.setDie1(42);

           System.out.println(dice); // This statement will not be executed!

          

        }

       

     } // end class RollFor2


Related Solutions

JAVA programming - please answer all prompts as apart of 1 java assignment. Part A Create...
JAVA programming - please answer all prompts as apart of 1 java assignment. Part A Create a java class InventoryItem which has a String description a double price an int howMany Provide a copy constructor in addition to other constructors. The copy constructor should copy description and price but not howMany, which defaults to 1 instead. In all inheriting classes, also provide copy constructors which chain to this one. Write a clone method that uses the copy constructor to create...
JAVA programming- please answer all prompts as apart of the same java project Enums enumeration values()...
JAVA programming- please answer all prompts as apart of the same java project Enums enumeration values() and other utilities Part A Create an enumeration AptType representing several different types of apartment. Each type of apartment has a description, a size (square footage), and a rent amount. In the enumeration, provide public final instance variables for these. Also write a parameterized constructor that sets the values of these variables (doing this is just part of seeing up the enum) The apartment...
Assignment Description This assignment focuses on programming basics; expressions, variables, constants, methods, selection and loops. Danny...
Assignment Description This assignment focuses on programming basics; expressions, variables, constants, methods, selection and loops. Danny runs an ice cream shop in the inner suburbs of Melbourne. Due to the growing number of customers, Danny has decided to take on extra casual employees. In order to manage payroll for his employees, Danny has decided to develop an employee payroll management system. Details of each employee to be maintained in the system will include; employee id, name, gender (M or F),...
Coding in Java Assignment Write the following static methods. Assume they are all in the same...
Coding in Java Assignment Write the following static methods. Assume they are all in the same class. Assume the reference variable input for the Scanner class and any class-level variables mentioned are already declared. All other variables will have to be declared as local unless they are parameter variables. Use printf. A method that prompts for the customer’s name and returns it from the keyboard. A method called shippingInvoice() that prompts for an invoice number and stores it in a...
Coding Java Assignment Write the following static methods. Assume they are all in the same class....
Coding Java Assignment Write the following static methods. Assume they are all in the same class. Assume the reference variable input for the Scanner class and any class-level variables mentioned are already declared. All other variables will have to be declared as local unless they are parameter variables. Use printf. A method that prompts for the customer’s name and returns it from the keyboard. A method called shippingInvoice() that prompts for an invoice number and stores it in a class...
THIS IS JAVA PROGRAMMING Guessing the Capitals. Write a program Lab5.java that repeatedly prompts the user...
THIS IS JAVA PROGRAMMING Guessing the Capitals. Write a program Lab5.java that repeatedly prompts the user to enter a capital for a state (by getting a state/capital pair via the StateCapitals class. Upon receiving the user’s input, the program reports whether the answer is correct. The program should randomly select 10 out of the 50 states. Modify your program so that it is guaranteed your program never asks the same state within one round of 10 guesses.
COP 2800, Java Programming Assignment 6-1 Using Java create a program using the “Methods” we covered...
COP 2800, Java Programming Assignment 6-1 Using Java create a program using the “Methods” we covered this week. come up with a “problem scenario” for which you can create a “solution”. Utilize any/all of the examples from the book and class that we discussed. Your program should be interactive and you should give a detailed statement about what the “description of the program – purpose and how to use it”. You should also use a “good bye” message. Remember to...
Java Programming Create a program that prompts the user for an integer number and searches for...
Java Programming Create a program that prompts the user for an integer number and searches for it within an array of 10 elements. What is the average number of comparisons required to find an element in the array? Your program should print the number of comparisons required to find the number or determine that the number does not exist. Try finding the first and last numbers stored in the array. Run your program several times before computing the average.
Java Programming II Homework 2-1 In this assignment you are being asked to write some methods...
Java Programming II Homework 2-1 In this assignment you are being asked to write some methods that operate on an array of int values. You will code all the methods and use your main method to test your methods. Your class should be named Array Your class will have the following methods (click on the method signatures for the Javadoc description of the methods): [ https://bit.ly/2GZXGWK ] public static int sum(int[] arr) public static int sum(int[] arr, int firstIndex, int...
Java Programming Assignment 6-1 We have covered the “Methods” this week. Apply the concepts that we...
Java Programming Assignment 6-1 We have covered the “Methods” this week. Apply the concepts that we have learnt in class and come up with a “problem scenario” for which you can create a “solution”. Utilize any/all of the examples from the book and class that we discussed. You program should be interactive and you should give a detailed statement about what the “description of the program – purpose and how to use it”. You should also use a “good bye”...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT