Java Tutorial
In java programming, Math.random is used to generate random double number between 0 and 1.
This java program is used to generate the random numbers based on range user input and required numbers count user input.
import java.util.Scanner; import java.lang.*; public class RandomNumber { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Random Numbers"); System.out.println("--------------"); System.out.print("Enter range: "); String strRange = in.nextLine(); String[] rangeVal = strRange.split("-"); if (rangeVal.length !=2){ System.out.println("Invalid range format!"); return; } int min = Integer.parseInt(rangeVal[0].trim()); int max = Integer.parseInt(rangeVal[1].trim()); if (max<=min){ System.out.println("Invalid range format!"); return; } System.out.print("Enter required random numbers count: "); int count = in.nextInt(); System.out.println("Random Numbers in Range ('"+strRange+"')"); for(int i=0;i<count;i++){ int randomNum = (((int)(Math.random()*100)%(max-min))+min); System.out.print(randomNum + "\t"); } } }Output:
D:\Java_Programs>javac RandomNumber.java D:\Java_Programs>java RandomNumber Random Numbers -------------- Enter range: 10-20 Enter required random numbers count: 25 Random Numbers in Range ('10-20') 17 14 16 13 19 13 13 19 14 13 13 12 16 11 10 17 16 14 15 19 13 17 10 12 10
import java.util.Scanner; import java.lang.*; public class RandomNumber { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Random Numbers"); System.out.println("--------------"); System.out.print("Enter range: "); String strRange = in.nextLine(); String[] rangeVal = strRange.split("-"); if (rangeVal.length !=2){ System.out.println("Invalid range format!"); return; } int min = Integer.parseInt(rangeVal[0].trim()); int max = Integer.parseInt(rangeVal[1].trim()); if (max<=min){ System.out.println("Invalid range format!"); return; } System.out.print("Enter required random numbers count: "); int count = in.nextInt(); System.out.println("Random Numbers in Range ('"+strRange+"')"); int i=0; while (i<count){ int randomNum = (((int)(Math.random()*100)%(max-min))+min); System.out.print(randomNum + "\t"); i++; } } }Output:
D:\Java_Programs>javac RandomNumber.java D:\Java_Programs>java RandomNumber Random Numbers -------------- Enter range: 15-24 Enter required random numbers count: 25 Random Numbers in Range ('15-24') 20 22 21 18 15 15 18 20 21 17 16 19 23 23 21 17 19 19 18 20 19 21 19 22 18
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page