Java

OOP GUIDE / WORK

 

DICE CLASS

 

Topics

  • Implementing methods and a constructor.
  • Using this.

 

 

SOLUTIONS

 

 

public class Dice

{

   public int sides;  //number of sides on die

   public int value;  //value of top face of die

  

   public Dice(int sides)

   {

        this.sides = sides;

        roll();    //this will actually set value

   }

  

   public void roll()

   {

        value = (int)(Math.random() * sides) + 1;

   }

  

   public String toString()

   {

        return "D" + sides + " is showing " + value;

   }

 

   public static void main(String[] args)

   {

        Dice d6 = new Dice(6);

        System.out.println(d6);

        d6.roll();

        System.out.println(d6);

       

        Dice d20 = new Dice(20);

        System.out.println(d20);

        d20.roll();

        System.out.println(d20);

       

        Dice coco = new Dice(10);

        System.out.println(coco);

        coco.roll();

        System.out.println(coco);

   }

}