[英]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?如何在 Java 中生成一个 0 到 500 之间以 5 结尾的随机数? I'm fairly new to programming.
我对编程很陌生。
See Java Generate Random Number Between Two Given Values请参阅Java 在两个给定值之间生成随机数
Generate a random number between 0(included) and 50(excluded), multiply it by 10 and add 5.生成一个0(含)到50(不含)之间的随机数,乘以10再加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
.正如@Lino 指出的那样,在应用程序的生命周期内只使用一次
new Random()
或使用ThreadLocalRandom
是一种很好的做法。 Additionally, please consider https://stackoverflow.com/a/3532136/18980756 .此外,请考虑https://stackoverflow.com/a/3532136/18980756 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.