Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a random number generator function “ rand_integer” that returns a random i

ID: 3838947 • Letter: W

Question

Write a random number generator function “ rand_integer” that returns a random integer between -10 and 10. To test this function, declare a function Array named “rand_array with a size of 32, call the rand_integer function to generate 32 random numbers, and store these number in the array. Print out each item in the array as the program output. Write a random number generator function “ rand_integer” that returns a random integer between -10 and 10. To test this function, declare a function Array named “rand_array with a size of 32, call the rand_integer function to generate 32 random numbers, and store these number in the array. Print out each item in the array as the program output. Write a random number generator function “ rand_integer” that returns a random integer between -10 and 10. To test this function, declare a function Array named “rand_array with a size of 32, call the rand_integer function to generate 32 random numbers, and store these number in the array. Print out each item in the array as the program output.

Explanation / Answer

import java.util.ArrayList;
import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {
  
public static final void main(String... aArgs){
log("Random numbers range -10..10.");
/* range of random numbers*/
int START = -10;
int END = 10;
  
int rand_size = 32;
  
ArrayList<Integer> rand_array = new ArrayList<Integer>();
Random random = new Random();
  
for (int idx = 1; idx <= rand_size; ++idx){
rand_array.add(randomInteger(START, END, random));
}
System.out.println(rand_array);
log("Done.");
}
  
private static int randomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
return randomNumber;
}
  
private static void log(String aMessage){
System.out.println(aMessage);
}
}

Sample Output:

Random numbers range -10..10.
[2, 2, 0, -1, 7, -7, -8, -8, -4, -4, -1, -4, 2, -1, 3, 7, 1, 9, -4, 1, 0, 6, -2, 2, 7, 2, 1, 4, 5, -3, 7, 9]
Done.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote