I have to create a yahtzee program using java.
In this program I must compare face values every time the dice are rolled. I have an ArrayList
of 5 dices.
Is there any way to compare these die without extremely long if statements?
The if statements would have to compare 1 dice value to the other 4 then do that for the other 4 die as well. It will be very long and I'm sure it can be simplified but I don't konw how. Any help is appreciated with this issue. This is the dice Class
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: Sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue(int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getVal()
{
return faceValue;
}
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
I fixed my java code to include collections.sort
import java.util.*;
public class Yahtzee
{
public static void manin(String args[])
{
Die die1 = new Die();
Die die2 = new Die();
Die die3 = new Die();
Die die4 = new Die();
Die die5 = new Die();
Die placeholder = new Die();
int timeRolled = 0;
String myString;
Scanner scan = new Scanner(System.in);
System.out.println("Please press 'y' to play and 'n' to quit");
myString = scan.next();
if(myString == "y")
{
ArrayList<Integer> yahtzee = new ArrayList<>(5);
die1.roll();
die2.roll();
die3.roll();
die4.roll();
die5.roll();
yahtzee.add(die1.getVal());
yahtzee.add(die2.getVal());
yahtzee.add(die3.getVal());
yahtzee.add(die4.getVal());
yahtzee.add(die5.getVal());
Collections.sort(yahtzee);
}
}
}
How would I know compare these values to one another?