Java Math random() method
In this tutorial, we will learn everything about Java Math random() method. Java includes various library methods. The library methods or functions are the in-built methods provided to us which help us to perform our tasks easily, accurately, and quickly. These in-built functions are frequently used in Java. Math.random() method belongs to the in-built functions.
Math.random() in Java
Math random() method is included in the class Math under the package Java.lang. We can learn this in the form of cases:
First case:
It is the most general one. It is a method or function which returns a random number between 0 and 1 in a double data type value.
Syntax of the method:
<Return data type><variable>=<Function name()>;
In this way:
double d = Math.random();
This will return any random number generated between 0 and 1 to the variable d.
The complete code with user input using Scanner class:
import java.util.*; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); double d; System.out.println("Random number between 0 and 1"); d=Math.random(); System.out.println(d); } }
The output after executing the above code:
Random number between 0 and 1
0.4402153460635767
Second case:
We can generate any random number between 1 and the upper limit provided by us. The upper limit is the value up to which the random number will be generated.
In this way:
double r = (double)(Math.random()*d)+1;
This will generate a random number between 1 and n and return the value to the variable r.
The complete code:
import java.util.*; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); double d; System.out.println("Enter the upper limit"); d=in.nextDouble(); System.out.println("Random number between 0 and 1"); double r = (double)(Math.random()*d)+1; System.out.println(r); } }
The output after executing the above code:
Enter the upper limit
6
Random number between 0 and 1
2.3983867459467447
Third case:
We can generate any random number between limits like m and n where m is the lower limit and n is the upper limit. Both the values can be provided by the user.
In this way:
double r = (double)(Math.random()*(n-m))+m;
This will generate a random number between m and n and will return the value to the variable r.
The complete code:
import java.util.*; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); double m; System.out.println("Enter the lower limit"); m=in.nextDouble(); double n; System.out.println("Enter the upper limit"); n=in.nextDouble(); System.out.println("Random number between 0 and 1"); double r = (double)(Math.random()*(n-m))+m; System.out.println(r); } }
The output after executing the above code:
Enter the lower limit
10
Enter the upper limit
20
Random number between 0 and 1
19.865869869904387
Hope this tutorial was useful.
Also read: Guess The Number Game Using Java with Source Code
Leave a Reply