Search code examples
javarandomsettergetterdice

Java setter, getter (rolling a die)


I have some questions about java. There are two questions in the code (I left them as comments). Also what is the purpose of using setting and getting methods? Could you please explain it very briefly. I am a beginner. Thank you :)

public class Die
{
   private final int MAX = 6;  
   private int faceValue;  

   public Die()
   {
      faceValue = 1;

      //why do you set the faceValue as 1?
   }

   public int roll()
   {
      faceValue = (int)(Math.random() * MAX) + 1;
      //Why do we use MAX instead of just number 6?

      return faceValue;
   }

   public void setFaceValue (int value)
   {
      if (value > 0 && value <= MAX)
         faceValue = value;
   }

   public int getFaceValue()
   {
      return faceValue;
   }

   public String toString()
   {
      String result = Integer.toString(faceValue);
      return result;
   }
}

Solution

  • First of all you should use the code sample tag properly this is ugly to read like that. Using getter/setter methods will prevent the direct access to an instance variable. This is also called data hiding or encapsulation. As for your questions, the faceValue gets initialized with the value 1, you normaly do init things within the constructor. The second question Math.random will generate a number between 0-1 you are multiplying it with 6 which results into a number between 0 and 5. So you add +1 to have the range of 1-6.