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

holdAt20 : This method should mimic a single turn of Pig where the player rolls

ID: 3678203 • Letter: H

Question

holdAt20 : This method should mimic a single turn of Pig where the player rolls until a 1 is rolled or until the turn total is greater than or equal to 20

• input parameter(s): none

• return value: an integer value representing the number of points the player scored on this turn (ie, their turn total).

• output: your method should print the value of each roll the player takes. When the player's turn is over, the method should print out the total points scored.

• Examples:

• holdAt20() might generate the output:

Roll: 4

Roll: 6

Roll: 5

Roll: 5

Turn total: 20

In this case, the method should return 20 (the player's score for this turn)

Explanation / Answer


/***The java program PIGame that simulates single
* turn of pig game*/
//PIGame.java
public class PIGame {
   public static void main(String[] args) {
       //calling holdAt20 method from main
       holdAt20();
   }

  
   /**The method holdAt20 that rolls the dice and
   * until the player's total is greater than or equal
   * to 20. if the dice value is 1 then print the turn
   * total to zero otherwise to add the dice value to sum*/
   public static void holdAt20() {
       int sum = 0;
       int k = roll(6);
      
       while (sum <=20)
       {
           System.out.println("Roll: " + k);
           //Add k value to sum
           sum = sum + k;
           if (sum >= 20)
           {
               System.out.println("Turn total: " + sum);
               //come out of loop
               break;
           }
           else if(k==1)
           {
               //print the turn total to zero
               System.out.println("Turn total: " + 0);
               //come out of loop
               break;
           }
           else
           {
               //Calling roll method
               k = roll(6);
           }
       }              
   }

   /**The method roll that takes an integer and returns
   * a number in a range of 1 to 6*/
   private static int roll(int i) {      
       return (int)(Math.random()*6+1);
   }
}


--------------------------------------------------------------

Sample run1:

Roll: 5
Roll: 3
Roll: 4
Roll: 3
Roll: 4
Roll: 1
Turn total: 20


sample run2:

Roll: 6
Roll: 2
Roll: 5
Roll: 1
Turn total: 0