java - 变量之间的 Java 随机数
问题描述
我试图在这 3 个变量之间随机化(不是范围,而只是在这 3 个值之间)并将其存储到新变量中。
int randomProductDiscount() {
int disc1 = 25;
int disc2 = 35;
int disc3 = 50;
int productDiscount = (random between disc1 or disc2 or disc3);
return productDiscount;
}
任何帮助,将不胜感激。
解决方案
将它们放在一个数组中并获得随机索引:
static Random rand = new Random();
int randomProductDiscount()
{
int[] disc = {25,35,50};
return disc[rand.nextInt(disc.length)];
}
这可用于您希望从中随机选择的任意数量的值。
推荐阅读
- laravel - 在 Laravel 中填写显示先前填写的数据的表单后,使用什么来显示成功消息?
- javascript - 无法使用带有 X509 用户的 mongoose 连接到 Mongo DB
- android - Android-Firebase 数据未显示在 ArrayList 中
- azure - 如何在 Azure VM 上同时运行 2 个 VM 自定义脚本扩展
- python - Keras model.fit_generator() 提供 0.0% 的验证准确度
- git - 想要在 jira 页面上显示各自作者的 git 提交
- gitlab - 将项目推送到 Gitlab 但我无法推送布局
- algorithm - 无限棋盘井字游戏的最佳数据结构
- python - DRF ForeignKey 值未部分显示
- java - 为什么 Scala 有自己的内置库?