简体   繁体   中英

Generating a random number that ends with a certain digit in Java

How does one generate a random number between 0 and 500 that ENDS WITH 5 in Java? I'm fairly new to programming.

See Java Generate Random Number Between Two Given Values

Generate a random number between 0(included) and 50(excluded), multiply it by 10 and add 5.

import java.util.Random;
public class RandomFive {
    static Random rand = new Random();
    public static int randomFive() {
        return rand.nextInt(50) * 10 + 5;
    }
    public static int randomFiveFun() {
        int randomFive = 0;
        while ((randomFive = rand.nextInt(500)) % 10 != 5);        
        return randomFive;
    }
    public static int randomFivePresidentJamesKPolck() {
        return (rand.nextInt(50) * 2 + 1 ) * 5;
    }        
    public static void main(String[] args) {
        System.out.printf("Normal: %3d\n", randomFive());
        System.out.printf("Fun:    %3d\n", randomFiveFun());
        System.out.printf("PJKP:   %3d\n", randomFivePresidentJamesKPolck());
    }
}

As @Lino pointed out, it is a good practice to use new Random() only once during your application's lifetime or to use ThreadLocalRandom . Additionally, please consider https://stackoverflow.com/a/3532136/18980756 .

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