Explain the concept of java dice roll?

633    Asked by KatoSaito in Java , Asked on Oct 10, 2022

 I've written a basic dice program in Java which takes a number of faces then randomly selects a number within that boundary. Here is the code:

package com.georgegibson.diceroller;

import java.util.Random;
import java.util.Scanner;
public class DiceRoller
{
    public static void main(String []args)
    {
        Random dice = new Random();
        Scanner input = new Scanner(System.in);
        int faces;
        int result;
       System.out.println("Dice Rollern");
        System.out.println("How many faces does the dice have?");
        faces = input.nextInt();
        result = dice.nextInt(faces) + 1;
        System.out.println("nThe dice rolled a " + result + ".");
    }
}

Seeing as I am pretty new to Java (I come from C/C++ land), I should think this can be improved, but how?


Answered by Kaushik Chandra

In your code you have declared a variable dice which is a Random. This is an indication that you have a mismatch between the object and the implementation. The fact that you call it 'dice' implies you want something that is a Dice.... not a Random. A Dice should be able to "encapsulate" itself.


I would suggest a clean Java object oriented design would have a Dice class, something like:

public class Dice {
    private final Random rand;
    private final int faces;
    public Dice(int faces) {
        this.rand = new Random();
        this.faces = faces;
    }
    public int dice roll() {
        return 1 + rand.nextInt(faces);
    }
}

Now you have a class that represents a dice, and you can roll that dice, and you now have a main method that looks like:

public static void main(String []args)

{
    Scanner input = new Scanner(System.in);
    System.out.println("Dice Roller
");
    System.out.println("How many faces does the dice have?");
    Dice dice = new Dice(input.nextInt());
    System.out.println("
The dice rolled a " + dice.roll() + ".");
}

You can reuse that dice, or create other dice with a different number of faces.

Note, there's always going to be a discussion about the singular "Die", and the plural is "Dice". One Die, many Dice.... but I say "who cares" call it a Dice.... Creating a class called "Die" is just wrong :wink:



Your Answer

Interviews

Parent Categories