Monday, February 21, 2011

java program that generates random number of given length

The code below generates a random number of a required length and returns it. Here a while loop is utilised to to loop through a given no of times. You could use a for loop or a do while loop too. Within the while loop, the nextInt method is called on the random instance to generate a random number. This random number is appended to a string instance. You could improve the string manipulation performance by making use of a Stringbuilder. I will try to show an example which incorporates a StringBuilder at a later time.
public class Main {

    static int generate(int length){

        Random r = new Random();

         String number="";

         int counter=0;

         while(counter++< length) number+= r.nextInt(9);

        return Integer.parseInt(number);

    }

    public static void main(String[] args) {
   
        System.out.println(generate(8));

    }
}

1 comment:


  1. Hi,

    am Vinothkumar, i have a small dount to generate random number . is that when we give the length of the generating number in run time , the lenght should be assigin and when the user want 3 digit, if the number comes as 1 means it should be like 001 ,shall any one give me an idea to make that code in java

    ReplyDelete