1. Write four overloaded methods called randomize. Each method will return a ran
ID: 3661471 • Letter: 1
Question
1. Write four overloaded methods called randomize. Each method will return a random number based on the parameters that it receives:
randomize() - Returns a random int between min and max inclusive. Must have two int parameters.
randomize() - Returns a random int between 0 and max inclusive. Must have one int parameter.
randomize() - Returns a random double between min and max inclusive. Must have two double parameters.
randomize() - Returns a random double between 0 and max inclusive. Must have one double parameter.
Explanation / Answer
import java.util.Random;
/**
* @author Srinivas Palli
*
*/
public class RandomNumbers {
/**
* Method to Returns a random int between min and max inclusive
*
* @param min
* @param max
* @return
*/
public static int randomize(int min, int max) {
Random random = new Random();
int randomNum = random.nextInt(max - min) + min;
return randomNum;
}
/**
* Method to Returns a random int between 0 and max inclusive
*
* @param max
* @return
*/
public static int randomize(int max) {
Random random = new Random();
int randomNum = random.nextInt(max);
return randomNum;
}
/**
* Method to Returns a random double between min and max inclusive
*
* @param min
* @param max
* @return
*/
public static double randomize(double min, double max) {
Random random = new Random();
double randomVal = random.nextDouble();
double randomNum = min + (randomVal * (max - min));
return randomNum;
}
/**
* Method to Returns a random double between 0 and max inclusive
*
* @param min
* @param max
* @return
*/
public static double randomize(double max) {
Random random = new Random();
double randomVal = random.nextDouble();
double randomNum = 0 + (randomVal * (max - 0));
return randomNum;
}
/**
* main method test the methods
*
* @param args
*/
public static void main(String[] args) {
System.out.println("1.Random Int between min and max inclusive: "
+ randomize(10, 12));
System.out.println("2.Random Int between 0 and max inclusive: "
+ randomize(10));
System.out.println("3.Random Double between min and max inclusive: "
+ randomize(10d, 12d));
System.out.println("4.Random Double between 0 and max inclusive: "
+ randomize(1d));
}
}
OUTPUT:
1.Random Int between min and max inclusive: 11
2.Random Int between 0 and max inclusive: 4
3.Random Double between min and max inclusive: 10.396489751187348
4.Random Double between 0 and max inclusive: 0.916620594458645
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.