'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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1