In this article, we emulate N Dice roller. Given N, the task is to create a Java program which outputs N random numbers where each number is in the range 1 to 6 inclusive. Such type of emulation can be used in games and apart from that some similar variations of the problem statement can be used in several other applications.
Example1:
Enter the Number of dice: 4 Hey Geek! You rolled: 3 2 1 6 Total: 12
Example2:
Enter the Number of dice: 2 Hey Geek! You rolled: 1 6 Total: 7
Note: The output may change since we are using random numbers.
Approach:
Here, we use the Random object in Java to generate random integers in the range 1 to 6 inclusive and execute a loop to generate such random numbers N times.
Implementation
C++
#include <cstdlib>#include <ctime>#include <iostream>using namespace std;int main(){Â Â Â Â int numberOfDice, total = 0;Â
    cout << "Enter the Number of dice: ";    cin >> numberOfDice;       // calling srand() with time() function for seed    // generation    srand((unsigned)time(0));    cout << "Hey Geek! You rolled: ";Â
    for (int i = 0; i < numberOfDice ; i++)    {               // Generating the random number and storing it        // in the 'randomNumber' variable        int randomNumber = (rand() % 6) + 1;        total += randomNumber;        cout << randomNumber << " ";    }    cout << "\n"         << "Total: " << total << "\n";    return 0;}Â
// This code is contributed by anurag31. |
Java
import java.util.Random;import java.util.Scanner;Â
public class Main {Â Â Â Â public static void main(String args[])Â Â Â Â {Â Â Â Â Â Â Â Â System.out.print("Enter the number of dice: ");Â
        // Initializing the Scanner object to read input        Scanner input = new Scanner(System.in);        int numberOfDice = input.nextInt();Â
        // Initializing the Random object for        // generating random numbers        Random ranNum = new Random();Â
        System.out.print("Hey Geek! You rolled: ");        int total = 0;        int randomNumber = 0;Â
        for (int i = 0; i < numberOfDice; i++) {Â
            // Generating the random number and storing it            // in the 'randomNumber' variable            randomNumber = ranNum.nextInt(6) + 1;            total = total + randomNumber;            System.out.print(randomNumber);            System.out.print(" ");        }Â
        System.out.println("");        System.out.println("Total: " + total);        input.close();    }} |
Â
Â
Output
Â
Â
Time Complexity: O(N)
Â
Auxiliary Space: O(1)
Â
Â

