wood burning stoves 2.0*
The moose likes Java in General and the fly likes randon number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "randon number" Watch "randon number" New topic

randon number

john mor

Joined: Mar 06, 2005
Posts: 11
I try to print out 6 random numbers from 40 numbers
ex( 20,5,1,40,31,29)
the program which I have writen is ok, but I don't want that the program writes a random number more than one time.
ex 20,5,1,40,31,29) is ok
ex 20,5,5,40,31,29) is wrong. // how do I fix it?
Mark Van Tuyl
Ranch Hand

Joined: Mar 22, 2002
Posts: 60
Once a number has been selected, set it to -1 (or some other invalid value). Before displaying a number, make sure it's valid. Otherwise, select another.

<a href="http://www.catb.org/~esr/faqs/smart-questions.html" target="_blank" rel="nofollow">How To Ask Smart Questions</a>
john mor

Joined: Mar 06, 2005
Posts: 11
If I want to print out 6 nbrs

for(int i=0; i<6; i++)
and set a nbr to -1
the program dose not print out 6 different nbr, may be 5 or 4 nbrs.
Mark Van Tuyl
Ranch Hand

Joined: Mar 22, 2002
Posts: 60
Correct. If you have selected an invalid number, you must decrement the counter.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13884

What does your code look like? How do you store those 40 numbers in your program; in an array or one of the Java collections?

If you have the numbers in a java.util.List, you can use the method java.util.Collections.shuffle(...) to shuffle the elements in the list, and then you just take the first 6 numbers out of the shuffled list.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
I agree. Here's the link: http://aspose.com/file-tools
subject: randon number
Similar Threads
Assignment help
AP Computer Science assignment help
how to generate random numbers ? Random class always generate same number....
Creating random Unique values
Minimum and maximum random number?