Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java lotto with Math.random

807597Feb 17 2005 — edited Feb 20 2005
I am playing around with a small program that I have called Lotto. It generates 8 random numbers between 1 and 45 and prints them out. However, I have noticed that a number gets repeated within the loop, ie 22 appears twice.
what would be the best way to prevent this from happening?
Thankyou for any help. Oh, I have pasted the code below, feel free to comment on any part of it as well.
Thanks again.

public class Lotto
{
public static void main(String[] args)
{
int counter = 1;
int lottonum = 0;

while (counter <=8)
{
lottonum = (int) (Math.random()*45)+1;

switch (counter)
{
case 1:
System.out.println(" first number is " +"\t" +"\t" +lottonum);
break;
case 2:
System.out.println(" second number is " +"\t" +"\t" +lottonum);
break;
case 3:
System.out.println(" third number is " +"\t" +"\t" +lottonum);
break;
case 4:
System.out.println(" fourth number is " +"\t" +"\t" +lottonum);
break;
case 5:
System.out.println(" fifth number is " +"\t" +"\t" +lottonum);
break;
case 6:
System.out.println(" sixth number is " +"\t" +"\t" +lottonum);
break;
case 7:
case 8:
System.out.println(" supplementry numbers are " +"\t" +lottonum);
break;
}
counter +=1;
}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 20 2005
Added on Feb 17 2005
153 comments
939 views