# random number generator

• February 20th, 2011, 11:39 AM
java3
random number generator
I am new to java and have been asked to write a program that will generate random numbers between 10 and 20 and then stop when 18 is generated. Have been told to use a while statement and also to use Maths.Random and Maths.Round
[-O<
• February 20th, 2011, 12:53 PM
JavaPF
Re: random number generator
Hello java3,

You must of learnt the basics by now? Please create a class and show us the code you have attempted.

Show us where you are stuck and we can then go from there.

Heres some help with the while loop: http://www.javaprogrammingforums.com...ava-loops.html
• February 20th, 2011, 01:32 PM
java3
Re: random number generator
Ok this is what I've done. Like I said I am a complete novice to programming! When I run it it just keeps generating numbers non stop.

Code Java:

``` public static void main(String[] Args) {     // int nNum;       do { int n = 10; double dNum = n*Math.random(); //a random double between 0 and 10 int nNum = (int)Math.round(dNum); //a random int between 0 and 10 //System.out.println(number); } while (nNum != 8); System.out.println("the end"); }   }```
• February 20th, 2011, 01:34 PM
java3
Re: random number generator
I was wanting the number generator to stop when an 8 was produced
• February 21st, 2011, 11:00 AM
aussiemcgr
Re: random number generator
Limit your base case to confirm your algorithm. Basically, your algorithm could theoretically generate numbers forever if it never returns an 8.

So, to test your algorithm, instead of a base case of nNum != 8, try something like nNum < 3. This way you have a much more narrow window for the loop continuing and if the loop breaks you can confirm that the algorithm you have for generating a random number (larger than 2) is correct. If that never finishes, then we most likely have an algorithm issue since a number being generated that is larger than 2 is much more likely than the number 8 being generated.