# print random numbers without repetition

• 02-04-2010, 09:27 AM
princess.blue
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);
}
}
}
}
• 02-04-2010, 10:15 AM
javastuden
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
• 02-04-2010, 10:33 AM
Tolls
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
• 02-04-2010, 10:37 AM
javastuden
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