java - 如何在 Java 中返回 5 个随机的 "Powerball"数字

标签 java random for-loop

尝试在 Java 中返回 1 到 42 之间的 5 个随机数。

我目前有返回单个数字的逻辑(将其放入 ArrayList,但我想取消它。)我很难实现以返回 5 个随机数。我需要 5 个 for 循环吗?

    for (int i = 0; i < 10; i++) {
        int r = (int) (Math.random() * 42 + 1);
    }

我在这里看到了其他一些相关示例,它们似乎比我的需求所要求的要复杂。但是,我可能是错的。

最佳答案

只需将每个随机数放入一个数组并返回该数组...

public int[] powerBalls() {
     int[] balls = new int[5];
     for (int index = 0; index < 5; index++) {
          balls[index] = (int) (Math.random() * 42) + 1;
     }
     return balls;
}

关于java - 如何在 Java 中返回 5 个随机的 "Powerball"数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15916749/

相关文章:

language-agnostic - 随机排序数组

javascript - 将数组值推送到对象值

java - Logback 类 CircularityError

java - 比较两个arraylist的内容,将不匹配的内容存入另一个arraylist

用于生成具有给定名称和大小的随机数据的文件的 PHP 脚本?

javascript - 为什么 for..of/for..in 循环可以使用 const 而普通的 for 循环在 JS 中只能使用 let 或 var 作为其变量?

python - 如果我们在 python 的 for 循环中使用范围内的一些数学运算怎么办

java - LibGdx 渲染多个自定义 actor 性能

java - Spring启动性能问题

java - 随机分布在动态数组中