Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Homework 1) Create a die class. This is similar to the coin class , but ins

ID: 3782898 • Letter: J

Question

JAVA Homework

1)

Create a die class. This is similar to the coin class , but instead of face having value 0 or 1, it now has value 1,2,3,4,5, or 6. Also instead of having a method called flip, name it roll (you flip a coin but roll a die). You will NOT have a method called isHeads, but you will need a method (call it getFace ) which returns the face value of the die.

Altogether you will have one attribute (face), and the following methods: constructor (calls roll), roll, getFace.

Test it by writing a main method in which you roll 2 dice. If you get exactly 7 you win, 11 you lose, anything else roll both dice again until you either win or lose. in order to verify your program put a println in the loop so that every time you roll the dice you print out the total value.

Explanation / Answer

Die.java:


public class Die {

   private int face;

//constructor  
   public Die(){
       roll();
   }
  
   public void roll(){
       face=(int) Math.ceil((Math.random()*6));

//assigns a value between 1 and 6 to variable face
   }
  
   public int getFace(){
       return this.face;
   }
  
   public static void main(String args[]){
       Die d1;
       Die d2;
       int dieValue;
       for(int i=0;;i++){
           d1=new Die();
           d2=new Die();
           dieValue=d1.getFace()+d2.getFace();
          
           if(dieValue==7){
               System.out.println("You got "+dieValue+ " You won!! ");
               break;
           }
          
           else if(dieValue==11){
               System.out.println("You got "+dieValue+ " You lost!! ");
               break;
           }
          
           else
          
               System.out.println("You got "+ dieValue + " Rolling again! ");
       }
   }
}


Sample run 1:
You got 4
Rolling again!

You got 10
Rolling again!

You got 7
You won!!


Sample run 2:
You got 5
Rolling again!

You got 11
You lost!!