Java Program: Random Number Generator


Code Example 1:
package org.code2care.example;

import java.util.Random;

public class JavaRandomNumberGeneratorExample {

    public static void main(String[] args) {

        int noOfRandomNumbers = 10;
        generateRandomNumbers(noOfRandomNumbers);

    }

    public static void generateRandomNumbers(int noOfRandomNumbers) {

        Random random = new Random();

        for (int i = 0; i < noOfRandomNumbers; i++) {
            int randomNumber = random.nextInt();
            System.out.println(randomNumber);
        }
    }
}

Output:

-2125433095
836305817
-896405979
-1748201265
1330120858
20769789
1066517992
890512865
427376433
1248883616

Example 2: Generate random numbers between -100 to 100
    public static void generateRandomNumbers(int noOfRandomNumbers) {

        Random random = new Random();

        for (int i = 0; i < noOfRandomNumbers; i++) {
            int randomNumber = random.nextInt(-100,100);
            System.out.println(randomNumber);
        }
    }

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap