简体   繁体   中英

how to generate random numbers of specific digits?

I want to create a string of random numbers, where starting digit should be in the range from 1-9, which selects only single number, after that 2 random digits should be there from range 10-99. Means from range 1-10 let's say 1 is selected, and for 2nd and 3rd digit range should be between 10-99. Like 111, 245...
second digit should not be a single digit.

Tried Code:

            int random1 = new Random().nextInt((9 - 1) + 1) + 1;
            int random2 = new Random().nextInt((99 - 10) + 1) + 10;
            textSelectedFileName.setText(String.valueOf(random1+random2));

You generate your randoms like this:

Random r = new Random();
int ran1 = r.nextInt(9)+1; // Will give values from 1-9
int ran2 = r.nextInt(90)+10; // Will give values from 10-99

You then create your string like this: Opt 1 (Less recommended):

String s1 = String.valueOf(ran1);
String s2 = String.valueOf(ran2);
textSelectedFileName.setText(s1+s2);

Opt 2:

textSelectedFileName.setText(String.valueOf((ran1*100)+ran2));
Random rand = new Random();

int randomNum = rand.nextInt((maximumvalue - minmumvalue) + 1) + min;

You can also use the Math.random

int b = (int)(Math.random()*(max-min+1)+min)

for example (int)(Math.random()*(99-10+1)+10) //Generate random int value from 10 to 99

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM