this is my first post, although i have read this forum in the past. i have a slight problem with a random number generator that im sure is simple to fix.
my program has 1 button and 3 text boxes. when i click the button, a random number between 1 and 5 should appear in each of the three boxes. Every time i press the button, a random number does appear in each box, but it is the same number. ie. 1 1 1 or 4 4 4. what is wrong with my code that prevents 3 random numbers being generated, as i do not want to generate a random number and repeat it three times!
here is my code.
String food; Random f = new Random(); int randFood = (Math.abs(f.nextInt()) % 5) + 1; food=String.valueOf(randFood); jTextField1.setText(food);
String wood; Random w = new Random(); int randWood = (Math.abs(w.nextInt()) % 5) + 1; wood=String.valueOf(randWood); jTextField2.setText(wood);
String Ore; Random o = new Random(); int randOre = (Math.abs(o.nextInt()) % 5) + 1; Ore=String.valueOf(randOre); jTextField3.setText(Ore);
The problem is that you are creating a new Random object each time you push the button. This Random object is probably "seeded" with a similar value so you see the same number popping up each time. One fix is to move the Random object (f) to the class and make it a member variable. In fact, you might even want to make it static so that all instances of your class use the same random number generator.
Joseph's creating a Random each time, but only one and using it three times. I'd still recommend following your full advice and storing that Random in a class, but it shouldn't be that expensive to create (it's not a SecureRandom after all).
Joined: Feb 15, 2005
one of you did not see any difference between the origonal and fixed code so ill explain. hopefully can help people in the future.
the first code created 3 randoms - f w + o. this resulted in the 3 numbers being identical. the second code created one random - f. this one random was used instead of w + o. the end result was three different random numbers.