Question

In: Computer Science

Complete the implementation of the Die class. Note that the Die class uses an array to...

Complete the implementation of the Die class. Note that the Die class uses an array to represent the faces of a die.

You need to complete the no-argument constructor and the two methods compareTo and equals.

Code:

import java.util.Arrays;
import java.util.Objects;
import java.util.Random;


/*
* NOTE TO STUDENTS:
* The constructor that you need to complete can be found on line 47.
*
* The two methods you need to complete can be found at the end of this file.
*/

public class Die implements Comparable<Die> {

   /**
   * A random number generator to simulate rolling the die.
   * DO NOT CHANGE THE DECLARATION OF rng. THE UNIT TESTS RELY
   * ON BEGIN ABLE TO ACCESS THE RANDOM NUMBER GENERATOR.
   */
   Random rng = new Random();
  
   /**
   * The array of face values.
   */
   private int[] faces;
      
   /**
   * The current value of the die.
   */
   private int value;
  
   /**
   * The number of faces on a die.
   */
   public static int NUMBER_OF_FACES = 6;
  

   /*
   * You need to implement the no-argument constructor below, and the
   * methods compareTo and equals found at the end of the class.
   */
  
   public Die() {
      
   }
  

   private static boolean isInAscendingOrder(int[] a) {
       for (int i = 1; i < a.length; i++) {
           if (a[i] < a[i - 1]) {
               return false;
           }
       }
       return true;
   }
  

   public Die(int[] faces) {
       if (faces.length != 6) {
           throw new IllegalArgumentException();
       }
       if (!Die.isInAscendingOrder(faces)) {
           throw new IllegalArgumentException();
       }
       this.faces = Arrays.copyOf(faces, NUMBER_OF_FACES);
       this.value = this.faces[0];
   }
  

   public void setValueToFace(int face) {
       if (face < 0 || face >= NUMBER_OF_FACES) {
           throw new IllegalArgumentException();
       }
       this.value = this.faces[face];
   }
  

   public int value() {
       return this.value;
   }
  

   public int roll() {
       int idx = rng.nextInt(Die.NUMBER_OF_FACES);
       this.value = this.faces[idx];
       return this.value;
   }

  
   @Override
   public int hashCode() {
       return Objects.hash(this.value, this.faces);
   }

  
   /*
   * You need to implement the compareTo and equals methods below.
   *
   */
  
   @Override
   public int compareTo(Die other) {
      
   }
  

   @Override
   public boolean equals(Object obj) {
       // The method Arrays.equals may be useful for helping
       // to implement this method.
      
   }
  

}

Solutions

Expert Solution

Constructor implementation:

public Die() {
this.faces = new int[]{1,2,3,4,5,6};
this.value = this.faces[0];
}
  

Implementation of method compareTo(Die other):

@Override
public int compareTo(Die other) {

if(this.value == other.value)
return this.value;
else return 0;
}
  

Implementation of method equals(Object obj):

@Override
public boolean equals(Object obj) {
// The method Arrays.equals may be useful for helping
// to implement this method.
  
if(obj != null && obj.getClass()== this.getClass())
return true;
return false;
  
}

Complete Code:

import java.util.Arrays;
import java.util.Objects;
import java.util.Random;


/*
* NOTE TO STUDENTS:
* The constructor that you need to complete can be found on line 47.
*
* The two methods you need to complete can be found at the end of this file.
*/

public class Die implements Comparable<Die> {

/**
* A random number generator to simulate rolling the die.
* DO NOT CHANGE THE DECLARATION OF rng. THE UNIT TESTS RELY
* ON BEGIN ABLE TO ACCESS THE RANDOM NUMBER GENERATOR.
*/
Random rng = new Random();
  
/**
* The array of face values.
*/
private int[] faces;
  
/**
* The current value of the die.
*/
private int value;
  
/**
* The number of faces on a die.
*/
public static int NUMBER_OF_FACES = 6;
  

/*
* You need to implement the no-argument constructor below, and the
* methods compareTo and equals found at the end of the class.
*/
  
public Die() {
this.faces = new int[]{1,2,3,4,5,6};
this.value = this.faces[0];
}
  

private static boolean isInAscendingOrder(int[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1]) {
return false;
}
}
return true;
}
  

public Die(int[] faces) {
if (faces.length != 6) {
throw new IllegalArgumentException();
}
if (!Die.isInAscendingOrder(faces)) {
throw new IllegalArgumentException();
}
this.faces = Arrays.copyOf(faces, NUMBER_OF_FACES);
this.value = this.faces[0];
}
  

public void setValueToFace(int face) {
if (face < 0 || face >= NUMBER_OF_FACES) {
throw new IllegalArgumentException();
}
this.value = this.faces[face];
}
  

public int value() {
return this.value;
}
  

public int roll() {
int idx = rng.nextInt(Die.NUMBER_OF_FACES);
this.value = this.faces[idx];
return this.value;
}

  
@Override
public int hashCode() {
return Objects.hash(this.value, this.faces);
}

  
/*
* You need to implement the compareTo and equals methods below.
*
*/
  
@Override
public int compareTo(Die other) {

if(this.value == other.value)
return this.value;
else return 0;
}
  

@Override
public boolean equals(Object obj) {
// The method Arrays.equals may be useful for helping
// to implement this method.
  
if(obj != null && obj.getClass()== this.getClass())
return true;
return false;
  
}
  

}


Related Solutions

Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class...
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items. Anytime the list becomes full, double the size of the array.
Write a MIPS program that uses an implementation of quick sort to sort an array of...
Write a MIPS program that uses an implementation of quick sort to sort an array of numbers (Translate the following code into (Mars Assembly language). Quicksort Implementation - C int partition(int arr [] , int left , int right) { int i=left, j=right; int tmp; int pivot = arr[(left + right) / 2]; while (i <= j) { while (arr [ i ] < pivot) i ++; while (arr [ j ] > pivot) j −−; if (i <= j)...
write an implementation of the ADT stack that uses a resizeable array to represent the stack...
write an implementation of the ADT stack that uses a resizeable array to represent the stack items. Anytime the stack becomes full, double the size of the array. Maintain the stack's top entry at the end of the array. Please use c++ for this question.
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector...
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items.
9.11 LAB: Winning team (classes) Complete the Team class implementation. For the class method get_win_percentage(), the...
9.11 LAB: Winning team (classes) Complete the Team class implementation. For the class method get_win_percentage(), the formula is: team_wins / (team_wins + team_losses) Note: Use floating-point division. Ex: If the input is: Ravens 13 3 where Ravens is the team's name, 13 is the number of team wins, and 3 is the number of team losses, the output is: Congratulations, Team Ravens has a winning average! If the input is Angels 80 82, the output is: Team Angels has a...
Java the goal is to create a list class that uses an array to implement the...
Java the goal is to create a list class that uses an array to implement the interface below. I'm having trouble figuring out the remove(T element) and set(int index, T element). I haven't added any custom methods other than a simple expand method that doubles the size by 2. I would prefer it if you did not use any other custom methods. Please use Java Generics, Thank you. import java.util.*; /** * Interface for an Iterable, Indexed, Unsorted List ADT....
Make an Array implementation of a binary tree given the below class ArrayBinaryTree(BinaryTree): """Linked representation of...
Make an Array implementation of a binary tree given the below class ArrayBinaryTree(BinaryTree): """Linked representation of a binary tree structure.""" # -------------------------- nested _Node class -------------------------- class _Node: def __init__(self, element, parent=None, left=None, right=None): # -------------------------- nested Position class -------------------------- class Position(BinaryTree.Position): """An abstraction representing the location of a single element.""" def __init__(self, container, node): def element(self): def __eq__(self, other): # ------------------------------- utility methods ------------------------------- def _validate(self, p): """Return associated node, if position is valid.""" def _make_position(self, node): """Return Position...
Part I – Understand a Given Class (die class) (40 pts) • Download the die class...
Part I – Understand a Given Class (die class) (40 pts) • Download the die class (attached as usingDieClass.cpp), save it as LabUseDieClassFirstName1_FirstName2.cpp • Add proper opening comments at the beginning of the program. The comments must include the description of all three parts of this lab. You may want to modify the comments after all parts are done to be sure that it is done properly. • Run the program and answer the following questions: o How many objects...
Implement a class Polynomial that uses a dynamic array of doubles to store the coefficients for...
Implement a class Polynomial that uses a dynamic array of doubles to store the coefficients for a polynomial. Much of this work can be modelled on the C++ dynamic array of ints List that we discussed in class. This class does not need the method the overloaded += operator. Your class should have the following methods: Write one constructor that takes an integer n for the degree of a term and a double coefficient c for the coefficient of the...
Ch 5 Program 1: Sphere.java                Complete the implementation of the Sphere class based on the Diagram...
Ch 5 Program 1: Sphere.java                Complete the implementation of the Sphere class based on the Diagram below. Use the DecimalFormat class in Sphere.java to format your output in the toString method. Then download the tester application SphereTester.java from canvas to test your Sphere class. Do not change SphereTester.java. Sphere private double radius //radius of the sphere object private static int numSpheres //static or class variable. All Sphere objects share it public Sphere() //constructor . Initialize Sphere objects’ instance variable radius...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT