简体   繁体   中英

Using Random class to continue adding a random digit to a given number in Java

Given an integer, 234, how would I use a Random object to take this number and add only one random digit to it without making it a String. So the goal in this case would be to return a number that has 4 digits, with the last one being random. So for example the next number could be 2347. Then I want to take this number and do the same thing for 5 digits, for instance 23471. I know I can multiply by 10 to increase the digit count by 1, but this would not be random. The only methods I'm aware of for the Random class are nextInt(int n) and nextDouble().

Random generator = new Random();
int gameNum = 234;
public static int UpdateGameNum(int gameNum, Random)
{

gameNum = gameNum * 10 + generator.nextInt(10) would do it.

(The second argument to + is a random number in the inclusive range 0 to 9).

If you want to support negative gameNum , then use the more complex

gameNum = (gameNum >= 0 ? 1 : -1) * (Math.abs(gameNum) * 10 + generator.nextInt(10));

which effectively strips the sign, performs the concatenation of the random number, then reintroduces it.

You don't need to pass Random instance as an argument to updateGameNum()

Just multiply getNum with 10 and add a number from (0 - 9) by picking it randomly.

Random generator = new Random();
int gameNum = 234;
public static int UpdateGameNum(int gameNum)
{
    return ( gameNum *10 ) + generator.nextInt(10);
}

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