This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to put 5 random numbers in an array?  RSS feed

 
Matthew Burns
Greenhorn
Posts: 1
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone - new user and first post! I am writing a program to generate 5 random numbers and then store them in an array but I just can't figure out how to do that.

Here is a part of my code:


So this prints out 5 numbers but when the second print statement prints it only prints a 0...I am using the second print statement to try and verify an element. What am I doing wrong?

Kind regards,

Matt
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First off, you should always have you loop statements enclosed in braces. Like this:

In your example I suggest first setting the array value in one statement, and then printing the array value in a second statement.
 
Stefan Evans
Bartender
Posts: 1836
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The random number bit looks ok.
You store things in an array with an assignment statement.
For instance to put he number 42 into the third element of the array you would use :


Also, remember that indexes into an array start at 0, and go up to their size - 1.
Yes computers start counting at 0 rather than one.  Get used to it :-)

You have created an array of 5 ints with the int[5] declaraion.
These will be numArray[0], numArray[1], numArray[2], numArray[3] and numArray[4].

Can you see why this might not be entirely compatible with the for loop you have defined?
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
I think you are correct to use a Random object; unless you want a double between 0 inclusive and 1.0 exclusive I think you should not use Math#random.
Did you know that the Random object has a method which creates an IntStream? Introduced in Java8. You can get an array out of that? The 5L tells the method how many numbers to use; the 1 and 51 delimit the range, but as you already know your have to be careful about the ranges for such numbers.Read about the Random#ints() method here, which returns an IntStream and that has a method which creates your array directly.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!