Java Die, Counting Snake Eyes

1.1k Views Asked by At

Okay so for university, we have to Create two Die objects and roll them several times, counting the number of snake eyes that occur.

this is the code I have, I need some help as every time I compile and execute my program, I get a fail on it. I'm not 100% sure where i'm going wrong, and I Don't know entirely whether solutions will help unless you went to my university, but any help is appreciated :) Thanks.

The Fail is - http://i.imgur.com/ghcOlpP.png

(This is all coded in JPLIDE)

final int ROLLS = 500;
  int num1, num2, count = 0;

  Die die1 = new Die();
  Die die2 = new Die();

  for (int roll=1; roll <= ROLLS; roll++)
  {num1 = 1;
    num2 = 1;

    if (num1 == 1 && num2 == 1)    // check for snake eyes
      count++;
  }

  System.out.println ("Number of rolls: " + ROLLS);
  System.out.println ("Number of snake eyes: " + count);
  System.out.println ("Ratio: " + (float)count / ROLLS);
}}}

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 of this die.
  //-----------------------------------------------------------------
  public Die()
  {faceValue = 1;
  }

  //-----------------------------------------------------------------
  //  Computes a new face value for this die and returns the result.
  //-----------------------------------------------------------------
  public int roll()
  {faceValue = (int)(Math.random() * MAX) + 1;
    return faceValue;
  }

  //-----------------------------------------------------------------
  //  Face value mutator. The face value is not modified if the
  //  specified value is not valid.
  //-----------------------------------------------------------------
  public void setFaceValue (int value)
  {if (value > 0 && value <= MAX)
    faceValue = value;
  }

  //-----------------------------------------------------------------
  //  Face value accessor.
  //-----------------------------------------------------------------
  public int getFaceValue()
  {return faceValue;
  }

  //-----------------------------------------------------------------
  //  Returns a string representation of this die.
  //-----------------------------------------------------------------
  public String toString()
  {String result = Integer.toString(faceValue);
    return result;
  }
}
1

There are 1 best solutions below

2
On
for (int roll=1; roll <= ROLLS; roll++) {
num1 = 1;
num2 = 1;

if (num1 == 1 && num2 == 1)    // check for snake eyes
  count++;
}

This looks wrong. You set num1 = 1 and num2 = 1 and then check if both are equal to 1.. of course they are going to be equal to 1. I assume you meant to do something like

num1 = die1.roll() num2 = die2.roll()

This will at least make it so that you don't have snake eyes all 500 times.