This week's book giveaway is in the Performance forum.We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!

# Making an array with random numbers

Brandon Choate
Greenhorn
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?

David Newton
Author
Rancher
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
Posts: 12145
30
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.