【问题标题】:Make an array of random integers based on seed in Java在Java中根据种子制作一个随机整数数组
【发布时间】:2014-12-05 00:59:44
【问题描述】:

我需要创建一个整数数组(双精度和浮点数也可以,但我认为没有区别),因为我需要对它们进行某些数学运算,例如 * 和 +。我正在尝试用随机种子(即 1337 5443,我需要使用这些)填充数组,但我无法将随机变量转换为 int,也无法添加或乘以随机变量。所以基本上我需要从特定的种子中创建一个随机数数组,并且我还需要能够对列表中的每个元素进行数学运算。 这是我迄今为止所做的一个示例:

import java.util.Random;
public class{
public static int a [] = new int [101];
public static void main(String[] Args){
    for(int i = 0; i <= 100; i++){
        Random ran1 = new Random(1337);
        a [i] =  ran1;//THIS IS THE PROBLEM (incompatible types)
    }
    int sum = a[5] + a[8] * a[10];//this won't acctually be included, it's just an example
    }
}

【问题讨论】:

  • javadocs 是你的朋友,看看 Random 类的可用方法。
  • ran1.next()。 Random() 对象本身不是 int。

标签: java arrays random int random-seed


【解决方案1】:

您不会将Random 分配给int - 您需要调用nextInt,传递一个int,它给出了0 和绑定减去1 之间的范围。

a[i] = ran1.nextInt(10);  // 0-9 or substitute what you want for 10

【讨论】:

  • 那么我在 nextInt 的 () 中插入什么
  • 这取决于您想要生成的随机数的预期范围。如果您想要 0-9 范围内的数字,请选择 10。如果您想要0-99,请选择100。如果您想要任意范围,请参阅Generating random integers in a range with Java
  • 关闭问题是针对有问题的问题(不清楚、离题等)。这不是一件好事。但是,您可以将问题中的一个答案标记为“已接受”,方法是点击您认为对您最有帮助的答案旁边的复选标记。
猜你喜欢
  • 2012-02-10
  • 2011-08-21
  • 2021-03-23
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多