Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Making an array with random numbers  RSS feed

Brandon Choate
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(

Any tips on where I should start?

Also: Is that code for my average generator right?

Thanks in advance!
David Newton
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12510
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
You can thank my dental hygienist for my untimely aliveness. So tiny:
Thoughts on deprecation in Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!