Part 1: Create create the Java class representation of a die. http://en.wikipedi
ID: 3542153 • Letter: P
Question
Part 1:
Create create the Java class representation of a die. http://en.wikipedia.org/wiki/Dice
Use the java.util.Random class to generate random numbers. Please see the Java API for details:http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
The only attribute of this class should be: sides. It should be an integer and have a private scope.
Include a constructor that has "sides" as an parameter and sets the value of the "sides" attribute.
Include a roll() method that will return an integer. It should return an integer between 1 and sides, inclusive. This number should be randomly generated.
Include a toString method that will return "n-sided die", where n is replaced by the number of sides.
Part 2:
Create a "driver" class to test your class. This class will include the "main" method. (See the Library class of the Book.java example).
You will also be graded on correctness of syntax and code formatting. Please use the Java naming conventions athttp://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
The only attribute of this class should be: sides. It should be an integer and have a private scope. Include a constructor that has "sides" as an parameter and sets the value of the "sides" attribute. Include a roll() method that will return an integer. It should return an integer between 1 and sides, inclusive. This number should be randomly generated. Include a toString method that will return "n-sided die", where n is replaced by the number of sides. Create a "driver" class to test your class. This class will include the "main" method. (See the Library class of the Book.java example).Explanation / Answer
import java.util.Random;
//Die class
public class Die {
private int sides;//private member sides.
public Dice(int sides){
this.sides = sides;//set the number of sides
}
public int roll(){
Random rand = new Random();//Random number generator
int result = rand.nextInt(sides);//Create a random number between 0 and sides-1
return result+1;//add 1 to the above and return the same.
}
public String toString(){
return sides + "-sided die";
}
}