How does one generate a random number between 0 and 500 that ENDS WITH 5 in Java? I'm fairly new to programming.
            Asked
            
        
        
            Active
            
        
            Viewed 111 times
        
    1 Answers
4
            
            
        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.
 
    
    
        Franck
        
- 1,340
- 2
- 3
- 15
- 
                    2Always creating a `new Random()` is a very bad idea. You should either: 1) save it somewhere, 2) use `ThreadLocalRandom` – Lino May 13 '22 at 14:19