Write a Java Program which generates a random number
In Java, you can generate random numbers using the
java.util.Random
class or the Math.random()
method. Here are examples of both approaches:
Program 1 :(How to Generate Random Number in Java Using java.util.Random class)
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
// Create a Random object
Random random = new Random();
// Generate a random integer
int randomNumber = random.nextInt(); // Generates a random 32-bit integer
System.out.println("Random Integer: " + randomNumber);
// Generate a random integer within a specific range (e.g., between 1 and 100)
int minRange = 1;
int maxRange = 100;
int randomInRange = random.nextInt(maxRange - minRange + 1) + minRange;
System.out.println("Random Integer in Range: " + randomInRange);
// Generate a random double between 0 (inclusive) and 1 (exclusive)
double randomDouble = random.nextDouble();
System.out.println("Random Double: " + randomDouble);
}
}
Program 2 : (How to Generate Random Number in Java Using Math.random() method)
public class RandomNumberGeneratorMath {
public static void main(String[] args) {
// Generate a random double between 0 (inclusive) and 1 (exclusive)
double randomDouble = Math.random();
System.out.println("Random Double: " + randomDouble);
// Generate a random double within a specific range (e.g., between 1 and 100)
int minRange = 1;
int maxRange = 100;
double randomDoubleInRange = Math.random() * (maxRange - minRange + 1) + minRange;
System.out.println("Random Double in Range: " + randomDoubleInRange);
// If you need an integer value, you can cast the result
int randomIntInRange = (int) randomDoubleInRange;
System.out.println("Random Integer in Range: " + randomIntInRange);
}
}
Keep in mind that
Math.random()
returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive). If you need integers or a more flexible and configurable random number generation, using java.util.Random
might be a better choice.Output 1 :
Output 2 :
Comments
Post a Comment