Computer Science Canada

Random Number Question

Author:  rto [ Tue Dec 16, 2008 8:53 am ]
Post subject:  Random Number Question

Assignment : Write a program that uses a for loop and an array to store 100 random nitegers in the range of 0 to 1000. using a second for loop, calculate the average of the random numbers. have the program do this 10 times and print out the average each time.

What i have :

Java:

import java.io.*; // i use this in everyone of my codes , habit i suppose
import java.math.*;

class Array2
{
public static void mani (String [] args) throws Exception
{
int randNum [] = new int [1000];
int total = 0;

for (int i = 0; i < 100; i++) {

randNum[i] = (int) Math.random(1000)*1); //should i have a '+' before the 1000? If so, this seems to be giving the same error
total = total + randNum[i];
}
}
}


Im not too worried about the loss of precision error because that is easy enough to fix, the random number error im getting is annoying me though Smile

thanks

Author:  jernst [ Tue Dec 16, 2008 10:12 am ]
Post subject:  Re: Random Number Question

rto @ Tue Dec 16, 2008 8:53 am wrote:

Java:

randNum[i] = (int) Math.random(1000)*1); //should i have a '+' before the 1000? If so, this seems to be giving the same error


It looks like you are missing a bracket here. There is no match for the closing bracket at the end.

Author:  rto [ Tue Dec 16, 2008 11:12 am ]
Post subject:  RE:Random Number Question

(int) (Math.random()*1000)+1;

thats the aswer to my question, the +1 has to be OUTSIDE the brackets Smile thanks anyways guys

Author:  DemonWasp [ Tue Dec 16, 2008 11:40 am ]
Post subject:  RE:Random Number Question

Math.random takes 0 arguments. It returns a double in the range 0 - 0.99999..., what you're looking for is something like the following:

Java:

randNum[i] = (int) ( Math.random() * 1000 + 1 );


First, Math.random generates a number in its specified range 0 - 0.999...; then we "expand" that range to 0 - 999.999 by multiplying by 1000, we shift it by adding one - 1 - 1000.999...) - and then limit it by casting to integer: 1 - 1000.

A note on includes: it is generally considered good practice to only ever include what you really need (however tempting it may be to say import *). This is because you can sometimes use the imported file list to determine which of several identically-named classes is being used in the code. A modern editor designed for Java should have the capacity to do this automatically; in Eclipse it's Ctrl+Shift+O.

Edit: tried to use proper range notation, with square brackets. It didn't work.


: