Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Random Numbers and loops
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
LOL123




PostPosted: 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);
}
}
Sponsor
Sponsor
Sponsor
sponsor
TheGuardian001




PostPosted: 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.
TerranceN




PostPosted: 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.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: