Random generates same number in java

Posted by user1613360 on Stack Overflow See other posts from Stack Overflow or by user1613360
Published on 2014-06-08T09:15:58Z Indexed on 2014/06/08 9:24 UTC
Read the original article Hit count: 213

Filed under:
|

This is my java code.

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

class search
{
  private int numelem;
   private int[] input=new int[100];

public void setNumofelem()
{

  System.out.println("Enter the total numebr of elements");
  Scanner yz=new Scanner(System.in);
  numelem=yz.nextInt();

}
public void randomnumber() throws Exception
{
int max=500,min=1,n=numelem;
   Random rand = new Random(); 
 for (int j=0;j < n;j++)
 {

   input[j]=rand.nextInt(max)+1;

} 
}

public void printinput()
{ 
  int b=numelem,t=0;
  while(true)
if(b!=0)
{
   System.out.print("  "+input[t]);
     b--;
     t++;
}
else
break;
}

}
public class mycode
{
  public static void main(String args[]) throws Exception
{

   search a=new search();
   a.setNumofelem();
   a.randomnumber();
   a.printinput();
}
}

Now the function randomnumber() just returns the same number.The function executes perfectly if I execute it as a separate java program but fails miserably if I call it using an object.I have also tried the following variations but nothing works everything return the same number.

Variation 1:

public void randomnumber() throws Exception
    {
    int max=500,min=1,n=numelem;
       Random rand = new Random(); 
     for (int j=0;j < n;j++)
     {

            TimeUnit.SECONDS.sleep(1);

       input[j]=rand.nextInt(max)+1;

    } 
    }

Variation 2:

 public void randomnumber() throws Exception
    {
    int max=500,min=1,n=numelem;
       Random rand = new Random(); 
     for (int j=0;j < n;j++)
     {

    rand.setSeed(System.nanoTime());

       input[j]=rand.nextInt(max)+1;

    } 
    }

Variation 3:

 public void randomnumber() throws Exception
    {
    int max=500,min=1,n=numelem;
       Random rand = new Random(); 
     for (int j=0;j < n;j++)
     {

            TimeUnit.SECONDS.sleep(1);
    rand.setSeed(System.nanoTime());

       input[j]=rand.nextInt(max)+1;

    } 
    }

Sample input/Output:

Enter the number of elements:

5

23 23 23 23 23 23

© Stack Overflow or respective owner

Related posts about java

Related posts about random