Results 1 to 4 of 4
- 02-04-2010, 08:27 AM #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);
}
}
}
}
- 02-04-2010, 09:15 AM #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
- 02-04-2010, 09:33 AM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,448
- Rep Power
- 16
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, 09:37 AM #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
Similar Threads
-
How do I generate random numbers in a certain range using the random class?
By frasifrasi in forum New To JavaReplies: 8Last Post: 04-19-2009, 05:50 PM -
Help with random numbers
By checkmylongboarding in forum New To JavaReplies: 2Last Post: 01-12-2009, 05:47 AM -
Random numbers
By jithan in forum Advanced JavaReplies: 3Last Post: 06-14-2008, 02:04 PM -
random numbers without random class`
By carlos123 in forum New To JavaReplies: 4Last Post: 01-17-2008, 10:44 PM -
random numbers
By carlos123 in forum New To JavaReplies: 1Last Post: 12-22-2007, 02:56 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks