Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2009
    Location
    India
    Posts
    6
    Rep Power
    0

    Cool 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. #2
    javastuden's Avatar
    javastuden is offline Senior Member
    Join Date
    Nov 2009
    Posts
    160
    Rep Power
    5

    Default 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. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,853
    Rep Power
    19

    Default

    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. #4
    javastuden's Avatar
    javastuden is offline Senior Member
    Join Date
    Nov 2009
    Posts
    160
    Rep Power
    5

Similar Threads

  1. Replies: 8
    Last Post: 04-19-2009, 05:50 PM
  2. Help with random numbers
    By checkmylongboarding in forum New To Java
    Replies: 2
    Last Post: 01-12-2009, 05:47 AM
  3. Random numbers
    By jithan in forum Advanced Java
    Replies: 3
    Last Post: 06-14-2008, 02:04 PM
  4. random numbers without random class`
    By carlos123 in forum New To Java
    Replies: 4
    Last Post: 01-17-2008, 10:44 PM
  5. random numbers
    By carlos123 in forum New To Java
    Replies: 1
    Last Post: 12-22-2007, 02:56 AM

Posting Permissions

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