How to Generate Random Number in Java

How to Generate Random Number in Java

Approach: Using Math

Java



public class RandomNumber {
    public static void main(String[] args) {
        double num = Math.random();
        System.out.println(num);
    }
}

Approach: Generate a random number in between two number

Java



public class RandomNumber {
    public static void main(String[] args) {
        int start = 100, end = 200;
        int num = (int) (Math.random() * (end - start + 1) + start);
        System.out.println(num);
    }
}


No comments:

Post a Comment