In: Computer Science
Write a program that uses a custom function to generate a
specified number of random integers in a specified
range. This custom function should take three
arguments; the number of integers
to generate, the lower limit for the range, and
the upper limit for the range. Values for these
arguments should be entered by the user in main. The custom
function should display the random integers on one line separated
by single spaces. The function should also report how many numbers
were even and how many were odd.
Finally, the function should calculate the total
of the random integers and return this total back to
main where it will be printed. User inputs in main are
shown in blue.
Sample Output
How many integers are to be generated 8
Enter the lowest integer desired 10
Enter the highest integer desired 20
16 14 19 20 12 15 18 18
6 evens and 2 odds were generated
The total of those 8 random numbers is 132
import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
int result =
customFunction(8,10,20);
//result variable will give the total sum
//
System.out.println("The total of
those 8 random numbers is "+result);
//above print statement can be changeable based on user
requirement
}
public static int customFunction(int no,int lower,int
upper)
{
Random rand = new Random();
int num ,randnum ,even=0,odd=0,total=0;
//rand is a random object to create random
numbers
for (int i=0 ; i<no ; i++ ){
//i is a loop iteration variable
num = rand.nextInt();
//num will generate random number
randnum = lower + (int)(Math.random() * ((upper -
lower) + 1));
//we have other ways to generate random number in given
range.
// the above step will give the number in between the
given range
//if the given number is even it is counted on even
variable and same as odd
if (randnum%2==0)
even++;
else
odd++;
//in total variable we sum up all the numbers
total+=randnum;
//printing the numbers
System.out.print(randnum+" ");
}
System.out.println();
System.out.println(even+" evens and "+odd+" odds were
generated");
return total;
}
}