In: Computer Science
in Java Write a method called randomNumber that returns a random floating-point number in the range of [-20.0, 50.0). (hints: use Random class in the method)
I have coded the method randomNumber() as per specification and it is given below
public static double randomNumber() {
Random rand = new Random();
double min = -20.0, max = 50;
return min + rand.nextDouble() *
(max - min + 1);
}
To test that function, I have written the main() method as well. So
you run this code.
RandomNum.java
-----------------
public class RandomNum
{
public static double randomNumber() {
Random rand = new Random();
double min = -20.0, max = 50;
return min + rand.nextDouble() *
(max - min + 1);
}
public static void main(String[] args) {
System.out.println("Generating 10
random numbers between -20.0 and 50.0");
for(int i = 1; i <= 10;
i++)
System.out.println(randomNumber());
}
}
output
-----
Generating 10 random numbers between -20.0 and 50.0
-15.0698547159618
-1.0377579310862828
39.55919323170632
20.833752383962484
39.657093777193964
33.93026732784858
11.417199650024767
-8.539447874452527
30.298596656006687
48.4347660758347