Android Generating Random Number and Random Color with range in java

Today I will let tell you how to get a random number in android with just 2 to 3 line of code. so there is a built-in function in a Java language called random function this function help use to get random number every time we call it.
To get the idea of here is the sample code

[Random random = new Random();]

we have created an object of random function now if we want to get Integer number simply add

[int i = random.nextInt()]

this will add some random number to your variable. Now let's create a random number with a minimum and maximum range
there is a formula for it ((max-min) + 1) + min) . let's understand this formula with an example

[
final int min = 100;
final int max = 200;
Random random = new Random();
int i = random.nextInt((max - min) + 1) + min;
]

this code will return you number range from 100 to 200

Now same method we will you to get random color.

[
private int getRandomColorCode() {
final int min = 160;
final int max = 256;
Random random = new Random();
return Color.argb(150, random.nextInt((max - min) + 1) + min,
random.nextInt((max - min) + 1) + min,
random.nextInt((max - min) + 1) + min);
}]

so that is it for today.
Thank you for your time.

No comments:

Powered by Blogger.