Search code examples
javadice

How can I determine a straight of three dice in Java?


I'm making a Java program that rolls three dice and then determines whether it's a three pair, straight, or pair. How can I determine whether it's a straight or not?

static int d1, d2, d3;
static int wins, loses, ties, rounds;

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    char answer;

    welcome();
    while (answer != 'n') {
        DieGame.d1 = rollDie(1, 7);
        DieGame.d2 = rollDie(1, 7);
        DieGame.d3 = rollDie(1, 7);

        printDice(d1, d2, d3); 

        if (isTriple(d1, d2, d2)) {
            wins++;
        }

        else if (isStraight(d1, d2, d3)) {
            wins++;
        }


    }
}


public static boolean isStraight(int d1, int d2, int d3) {

    }

Here's just some of the code. Obviously there are other methods but I'm struggling with determining a straight. We aren't on arrays yet so I can't use that.


Solution

  • Something like this should work

    public boolean isStraight(int d1, int d2, int d3) {
       int min = getMin(d1, d2, d3);
       int mid = getMid(d1, d2, d3);
       int max = getMax(d1, d2, d3);
    
       if((max - mid) == 1 && (mid - min) == 1) {
         return true;
       } else {
         return false;
       }
    }
    

    Where getMin, getMid, and getMax return the minimum, middle, and maximum values. Since you haven't gotten to arrays, I'll assume you can't use Math.min(), etc. So, those would look like the following.

    public int getMin(int d1, int d2, int d3) {
      int min = d1;
      if (d2 < min) {
        min = d2;
      }
      if (d3 < min) {
        min = d3;
      }
      return min;
    }
    

    And so on...