将值拆分为两个随机数

时间:2017-04-17 01:19:32

标签: java random

我正在用Java创建一个随机图书目录,我打算将书籍套餐的随机生成价格值分成两个单独的值(代表两本书的各个包)。

例如。随机生成的书籍包42花费80美元,该包装中的两本书的单独价格花费$ X和$ Y.这是我的代码的摘录:

public class MultiAgent {

int maxBookID = 50;
int maxBookPrice = 100;
int maxNumItems = 50;

void buildCatalogue() {

    int numItems = rand.nextInt(maxNumItems);
    while (bookCatalogue.size() < numItems) {
        int ranID = rand.nextInt(maxBookID);
        bookCatalogue.put(String.valueOf(ranID), rand.nextInt(maxBookPrice));

    }

    for (Object key : bookCatalogue.keySet()) {

System.out.println("Package ID: " + (String) key + "; price value: " + bookCatalogue.get(key)); //The individual values of the two books should print here
    }

}
}

如何将生成的价格值拆分为两个随机值?

1 个答案:

答案 0 :(得分:3)

0.01.0

之间生成random float
float r = rand.nextFloat();

用它来分割你的价值:

float priceBook1 = packagePrice * r;
float priceBook2 = packagePrice * (1-r);

示例/解释

我们说packagePrice100r最终为0.4

priceBook1 = 100 * 0.4;      // 40
priceBook2 = 100 * (1-0.4);  // 60 

但是,请注意,其中一本书可能最终没有成本(在r0.0的情况下)。如果您想阻止这种情况,请查看问题的几个可用问题/答案之一,例如"Generating a random double number of a certain range in Java"