Can any one help me writing code which can only creat three digit random number not two digit or one digit number? Following code creates 3 digti but also creats two and one digit number..

public class random 
{
    public static void main (String [] args) 
    {
        double n = Math.random();
        long n3 = Math.round(Math.random()*1000);
        System.out.println (n3);
    }   
}

Do you mean a number without leading zeros, or without any zeros in it anywhere?

Try changing

long n3 = Math.round(Math.random()*1000);

whith

long n3 = Math.round(Math.random()*(999 - 100) + 100);

You'll need to define a range. One way of doing that is by this:

Math.random() * (Max - Min) + Min

where Max would be the maximum three digit number, and Min the lowest three digit number, hence Max = 999 and Min = 100.

Edit:
A quick verification:

public class random 
{
    public static void main (String [] args) 
    {
        for (int i=0;i<99999999;i++){
            long n3 = Math.round(Math.random()*(999-100)+100);
            if (n3 < 100 || n3 >=1000)
                System.out.println (n3);
        }
    }   
}

If you want integer values from Random you should use nextInt rather than rounding a random float - see the API doc for Random to appreciate the extra stuff needed to get good random ints.

@Lucaci Andrew
Thanks this works. But why we are adding min and also subtracting min? What difference does it makes?

You're adding the min at the end, because the numbers generated are in range 0 to 899. So, if generated the number 0, adding 100 will give us the lowest three digit number, and if generating 899, adding 100 will give us the 999, meaning the maximum three digit number.

Ok thanks for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.