aspose file tools*
The moose likes Beginning Java and the fly likes Making an array with random numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Making an array with random numbers " Watch "Making an array with random numbers " New topic
Author

Making an array with random numbers

Brandon Choate
Greenhorn

Joined: Mar 06, 2009
Posts: 14
Hello again.

I am currently working with arrays and array lists. I want to make a seven point array, all of which will be a random number.
Each of these will represent a temperature.

The Code Is Here:



I know how to make random numbers, but I do not know how to translate that into something that will work in an array.

I keep getting this error message when I try to run it:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ArrayOfTemperatures.main(ArrayOfTemperatures.java:19)


Any tips on where I should start?

Also: Is that code for my average generator right?

Thanks in advance!
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

The first thing to realize is that Java arrays are zero-based, not one-based. In other words, the first element is at index 0, not 1.

As far as if your average algorithm is correct a simple web search should turn up how to compute averages. You may want to consider using a "for" loop, however, rather than doing it manually.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

if you create an array of size 7, they are accessed as elemets 0-6, not 1-7. That's why you're getting the 'out of bounds' error.

You certainly CAN hard-code to add elements [0] - [6], but...

What happens if you want 30 elements? or a thousand? or 10,000?

There are two neat things you should check out. One is that an array can tell you how many elements it holds. From your example, you could say temp.length and get the number 7.

Then, you can write a loop that will run a certain number of times, and each time it could access a different element. So, you could write a loop that adds the 'current' value to a 'total' value. When the loop is done, your 'total' will have the sum of every element. you can then divide by the number of elements in the array.

By doing it this way, you can change the size of your array all you want, and you never have to touch the code that calculates the average.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Making an array with random numbers