Random Numbers in Java

In today's tutorial, we are going to cover how to generate random numbers in Java. Random numbers are used for a wide number of applications. They can be used for random sampling, simulations, generation of keys, lotteries, and games. One of the most common uses for random numbers is in video gaming. The outcomes of many events are determined by a random number generator. One of the simplest applications of random numbers is simulating a dice roll. That is what we will simulate in this application today. As always, pay close attention to comments for notes.
  1. import java.util.Random; //imports the random class for generating numbers
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class dice
  6. {
  7.  
  8.         public static void main(String[] args)
  9.         {
  10.  
  11.                 Scanner console = new Scanner(System.in);
  12.  
  13.                 System.out.println("\nPress Enter to roll two dice.");
  14.  
  15.                 console.nextLine(); //necessary to hold the program until user presses enter
  16.  
  17.                 Random randy = new Random(); //creation of random object called randy
  18.  
  19.                 int roll1 = randy.nextInt(6) + 1; //rolls a 6 sided die from 0 to 5;
  20.  
  21.                 int roll2 = randy.nextInt(6) + 1;
  22.  
  23.                 int totalRoll = roll1 + roll2;
  24.  
  25.                 System.out.println("\nYou have rolled a " + roll1 + " and a " + roll2 + ".\nThe total of your roll is " + totalRoll + "."); //final output to user
  26.  
  27.         }
  28.  
  29. }
As a side note for future reference, both the scanner and random classes may be imported at once (among other classes) with the following line of code: import java.util.*; Additionally, placing "\n" in a line of output is useful for formatting. This creates a line break in the output text. When it comes to generating random numbers, by default the pool of numbers starts with 0. If you wish to make the numbers begin with 1, all you must do is place +1 after the number generator, such as in the following: int roll = randy.nextInt(100) + 1; This creates a simulated 100-sided dice roll. Without the +1, you would get a number between 0 and 99. Experiment with different numbers and see your results. Try using this to make your own random number generator for your own uses.
Tags

Add new comment