Thread: print random numbers without repetition

1. print random numbers without repetition

hii..i want to print 6 numbers randomly...the program for dat is below:

//to print 6 random numbers in the range 1 to 49

public class PrrintRandom
{
public static void main(String[] args)
{
int i;
for (i=0;i<=6;i++)
{ int n=(int)(Math.random()*49)+1;
System.out.println(n);
}
}
}

above code is running fine...but i m getting duplicate numbers
so the new code i wrote is not working ...pls help me whre i m going wrong:

//to print 6 random numbers without repetition

public class NewRandom
{
public static void main(String[] args)
{
int i,j,a[]={};
for (i=0;i<6;i++)
{ int n=(int)(Math.random()*49)+1;
a[i]=n; //error in ths line
System.out.println(n);
}
for (i=0;i<6;i++)
{
for (j=0;j<6;j++)
while(i!=j)
{ if (a[i]==a[j])
System.out.println((int)(Math.random()*49)+1);
}
}
}
}

2. please check is this correct or not

hi
public class NewRandom
{
public static void main(String[] args)
{
int i,j;
int a[]=new int[6];
for (i=0;i<6;i++)
{ int n=(int)(Math.random()*49)+1;
a[i]=n; //error in ths line
System.out.println(n);
}
/*for (i=0;i<6;i++)
{
for (j=0;j<6;j++)
while(i!=j)
{ if (a[i]==a[j])
System.out.println((int)(Math.random()*49)+1);
}
}*/
}
}

please check is this correct or not

3. Moderator
Join Date
Apr 2009
Posts
13,220
Rep Power
23
Have a List<Integer> prepopulated with the Integers 1-49...Math.random based on the length of the list, and do a remove at that index.
:)

This is not terribly scaleable it has to be said...:D

4. use set

hi
see the set The Set Interface (The Java™ Tutorials > Collections > Interfaces)
in that no duplicate will not allow feature has to add by logic

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•