To get a random number between 1 and 100 in Java, you can use the java.util.Random
class.
Generating a Random Number Between 1 and 100
Here's a breakdown of how to do it, including code and explanation based on the provided reference:
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Create an instance of the Random class.
Random randomNum = new Random();
// Generate a random number between 0 (inclusive) and 100 (exclusive), and then add 1.
int showMe = randomNum.nextInt(100) + 1;
// Print the random number.
System.out.println("Random number between 1 and 100: " + showMe);
}
}
Explanation:
- Import the
Random
class: The code starts by importing thejava.util.Random
class, which is necessary for generating random numbers. - Create a
Random
object: An instance of theRandom
class is created usingRandom randomNum = new Random();
. This object will be used to generate random numbers. - Generate a random number: The
nextInt(100)
method generates a random integer between 0 (inclusive) and 100 (exclusive). To get a number between 1 and 100 (inclusive), we add 1 to the result:randomNum.nextInt(100) + 1
. - Print the result: The generated random number is then printed to the console using
System.out.println()
.
Example
The code above will output a random number between 1 and 100 each time it is run. For example:
Random number between 1 and 100: 42
Random number between 1 and 100: 87
And so on.