Tuesday, 13 February 2018

Write a Java Program to Find Random Number

package com.tutorial4u;

import java.util.Random;
import java.util.Scanner;

public class RandomNumber {
     public static void main(String[] args)
    {
        int maxRange;
        Scanner sc = new Scanner(System.in);
        Random rand = new Random();
       
        System.out.print("Please enter maximum range: ");
        maxRange = sc.nextInt();
       
        for(int i=1; i<=10; i++)
        {
            System.out.println(rand.nextInt(maxRange));
        }
    }


}


Output:

Please enter maximum range: 500
223
263
397
375
371
468
71
124
377
374

Note : Sometimes situation arises where random numbers are required to be generated between the ranges.

package com.tutorial4u;

import java.util.Random;
import java.util.Scanner;

public class RandomNumber {
     public static void main(String[] args)
    {
           Scanner sc = new Scanner(System.in);
        System.out.print("Please enter Minimum Range : ");
        int minRange = sc.nextInt();
        System.out.print("Please enter Maximum Range : ");
        int maxRange = sc.nextInt();
        Random rand = new Random();
        int value = rand.nextInt(maxRange - minRange) + minRange;
        System.out.println(value);
    }
}


Output :

Please enter Minimum Range : 1000
Please enter Maximum Range : 5000
4304


No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...