-
Random Integers
First off, I am a noob when it comes to programming java. I am a high school student, and have only taken a semester course on java. I am currently working on making a game with simple integer/picture tricks, but I need to know how to create a code that can randomize numbers in between set parameters. IE: A number in between 0 - 20.
-
Code:
import java.util.Random;
public class Test {
static Random seed = new Random();
public static void main(String[] args) {
test(0, 20);
test(5, 10);
}
private static void test(int low, int high) {
int min = Integer.MAX_VALUE;
int max = -Integer.MAX_VALUE;
int range = high - low +1;
for(int j = 0; j < 500; j++) {
int n = low + seed.nextInt(range);
if(n < min) min = n;
if(n > max) max = n;
}
System.out.printf("min = %d max = %d%n", min, max);
}
}
-
could you add some text explaining each part of that code please...I don't really understand about half of that (sorry, I am kind of garbage at java)
-
or if anyone could help out....
-
Its an idea of how to explore a question.
Code:
private static void test(int low, int high) {
// Find the lowest and highest random values.
// Save the extreme values in variables to print later.
// Initialize the minimum variable to the highest
// possible value for its type (data type [i]int[/i])
int min = Integer.MAX_VALUE;
// Initialize the maximum value to the lowest
// possible value for its data type.
int max = -Integer.MAX_VALUE;
// Compute random values in the range [low <= value <= high].
// This is the part you play with to get the results you want.
int range = high - low +1;
// Do enough runs to get definite accurate min and max:
for(int j = 0; j < 500; j++) {
int n = low + seed.nextInt(range);
// If the value "n" is lower than the
// current/last-saved value of "min"
// save the value of "n" in "min".
if(n < min) min = n;
// Update "max" with the highest value we find.
if(n > max) max = n;
}
// Print out the results.
System.out.printf("min = %d max = %d%n", min, max);
}
All of this was a journey to be able to write this:
Code:
int n = low + seed.nextInt(high - low +1);
with confidence.
-
that is still kind of confusing, idk if you want to waste any more time trying to explain it to me, but if you could that would be way nice (like which stuff I will need to modify to my own applet and stuff)
-
for example the integers and values, which ones do I change and which ones are supposed to be left untouched
-
The best way to figure out is to play with the code given in #2 above. When someone posts code that compiles and runs you can run it, make changes, experiment and learn how it works. Learning comes with tinkering and experimenting.
-