Generate a Random Number between 1 and 10 in Java
In Java, you can use the java.util.Random
class to generate random numbers between a range of values.
Here’s an example that generates a random number between 1 and 10 in Java:
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random rand = new Random();
int randomNumber = rand.nextInt(10) + 1;
System.out.println("Random number between 1 and 10: " + randomNumber);
}
}
Here,
- we first import the
java.util.Random
class, which provides methods for generating random numbers. - we then create a new
Random
object, which we’ll use to generate our random number. - to generate a random number between 1 and 10, we use the
nextInt()
method of theRandom
class, which returns a random integer between 0 (inclusive) and the specified value (exclusive) in this case 10.nextInt(10)
generates number between 0 and 9, so we add 1 to it to ensure that our random number is between 1 and 10.
To generate any random number between min
and max
.
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
int min = 5; // Minimum value
int max = 15; // Maximum value
Random rand = new Random();
int randomNumber = rand.nextInt(max - min + 1) + min;
System.out.println("Random number between " + min + " and " + max + "is : " + randomNumber);
}
}
Here, we used the max - min + 1
value as the argument to nextInt()
. This generates a random integer between 0 (inclusive) and (max - min) (inclusive). We add min
to the result to shift the range to start at min
. This ensures that the generated number is between min
and max
.