Computer Science Canada

Random Numbers and loops

Author:  LOL123 [ Sat Mar 27, 2010 3:40 pm ]
Post subject:  Random Numbers and loops

Ok I need to make a program that will output 20 random numbers and the average of those 20 numbers. The numbers are in between 1 and 40.
So in my code below I have it set up using a for loop and I want it to stop when counter is equal to 20 this does not work when I run the program it only out puts 1 random number I dont understand why it wont output mmore than once?
Would I have to use a do while loop for this to work correctly?
Thank you any help is welcomed.

Quote:


class RandomLoops
{
public static void main (String args [])
{
int num = 0;
int average = 0;
final int NUM_RANGE = 40;
final int MIN = 1;

for (int counter = 0; counter < 20; counter++)

num = (int)(Math.random () * NUM_RANGE) + MIN;
System.out.println ("Random number is " + num);
}
}

Author:  TheGuardian001 [ Sat Mar 27, 2010 4:03 pm ]
Post subject:  Re: Random Numbers and loops

Your for loop doesn't have any braces around it. This mean that only the line immediately after you start it is repeated. Put some braces around it and it should work fine.

Author:  TerranceN [ Sat Mar 27, 2010 4:06 pm ]
Post subject:  RE:Random Numbers and loops

First of all, use syntax tags like Barbarrosa said, so you can indent your code, making it much easier to read. Your problem is because without braces, a for loop only executes the next statement, and you want it to execute the next two, so you need to put braces around the code you want to be looped.


: