Random Numbers in Java
Submitted by GeePee on Friday, May 8, 2015 - 22:40.
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.
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.Random; //imports the random class for generating numbers
- import java.util.Scanner;
- public class dice
- {
- {
- console.nextLine(); //necessary to hold the program until user presses enter
- int roll1 = randy.nextInt(6) + 1; //rolls a 6 sided die from 0 to 5;
- int roll2 = randy.nextInt(6) + 1;
- int totalRoll = roll1 + roll2;
- System.out.println("\nYou have rolled a " + roll1 + " and a " + roll2 + ".\nThe total of your roll is " + totalRoll + "."); //final output to user
- }
- }
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.Add new comment
- 25 views