Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 4 weeks ago

# How do I make a Yahtzee Program in Java?

It needs to include the following:

Variables:private int d1 - Value of the 1st die private int d2 - Value of the 2nd die private int d3 - Value of the 3rd die private int d4 - Value of the 4th die private int d5 - Value of the 5th die private int score - Total score of the player so far private int rounds - Number of rounds to play (scanned)Methods:

public Yahtzee(int r) - initializing the instance variables (listed above) to appropriate values.

public boolean isFiveOfAKind()  - Check if the dice currently contain a five of a kind combo.

public boolean isFourOfAKind() - Check if the dice currently contain a four of a kind combo.

public boolean isThreeOfAKind() - Check if the dice currently contain a three of a kind combo.

I'm really struggling with this and new to Java, so any help will be deeply appreciated!

Relevance

The easiest way to get a random number from 1 to 6 in Java is:

d1 = 1 + (int)(6.0 * Math.random());

I'm no fan of using separate variables for the dice.  An array would work well for a case where the number of dice is fixed.  That means you need five assignment statements rather than a single loop to initialize all five dice.  When you get into testing for 3, 4, or 5 of a kind, the duplication of code gets much worse.

There's a cute method I came up with for classifying poker hands that works well here.  Count the total number of distinct pairs.  How many pairs of two different dice are equal.

int pairs = 0;

int[] dice = {d1, d2, d3, d4, d5}; // make an array for easier counting

for (int i=0; i<4; ++i) { // loop over all 0 <= i < j < 5 index pairs

for (int j=i+1; j<5; ++j) {

if (dice[i] == dice[j])

pairs += 1;

}

}

That looks at every pair of dice just once, and counts how many pairs were equal.  There are a total of 10 pairs, since C(5,2) = (5*4)/(1*2) = 20/2 = 10.

With all 5 dice equal, there will be 10 pairs.

With 4 dice equal, there will be 6 pairs.

With 3 dice equal, there will be 3 pairs, plus one more if the other two are equal.

Otherwise the pair count is 0 for all different, 1 for one pair or 2 for two pairs.

So, that one nested loop statement gives you all three categorizations.

• Login to reply the answers