首页 > 解决方案 > 变量之间的 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;

}

任何帮助,将不胜感激。

标签: javafunctionrandommethodsint

解决方案


将它们放在一个数组中并获得随机索引:

static Random rand = new Random();

int randomProductDiscount()
{
    int[] disc = {25,35,50}; 
    return disc[rand.nextInt(disc.length)];
}

这可用于您希望从中随机选择的任意数量的值。


推荐阅读