java随机数选择器

标签 java

我有一个作业要编写一个返回介于之间的随机数的方法 1 和 54,不包括参数中传递的数字。方法头是 具体如下:

public static int getRandom(int... numbers)

我无法使用比一维数组更高级的东西。

我的代码是:

public class PE13RandomNumberChooserVer2 {

    public static void main(String[] args) {

        int[] excludeNumbers = {1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18};
        int randomNumber = getRandom(excludeNumbers);
        System.out.println();
        System.out.println("Random number chosen: " + randomNumber);
    }

    public static int getRandom(int... excludeNumbers) {

        int random = 1 + (int)(Math.random() * (54 - 1) + 1);
        System.out.println("Numbers to exclude: ");

        for (int i = 0; i < excludeNumbers.length; i++) {
            System.out.print(excludeNumbers[i] + " ");
            while (excludeNumbers[i] == random) {
                random = 1 + (int)(Math.random() * 54);
                System.out.println("\n(for test only) next random number: " + random);
            }
        }

        return random;
    }

}

示例运行表明我的逻辑是错误的:

(for test only) initial random number: 8
Numbers to exclude: 
1 2 3 4 5 6 7 8 
(for test only) next random number: 12
11 12 
(for test only) next random number: 3
13 14 15 16 17 18 
Random number chosen: 3

它仅检查 random 是否等于数组中的当前项目,不考虑它可以等于已检查的列表中的前一个项目的情况。

随机生成的数字的最终结果应该与数组中的数字不同。 非常感谢任何如何修复它的建议。

最佳答案

以下内容即可实现:

    private final Random rand = new Random();

    public int getRandom(int min, int max, int... excludeNumbers) {
        int random = rand.nextInt(max - min + 1 - excludeNumbers.length) + min;
        for (int exc : excludeNumbers) {
            if (random >= exc) {
                random++;
            }
        }
        return random;
    }

观察它如何仅生成单个随机数并且不需要拒绝循环。

请注意,minmax 均包含在内。另请注意,excludeNumbers 必须按升序显示。

关于java随机数选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904484/

相关文章:

java - 使用 JTable 和 JTextField 打印 JPanel

java - 嵌入式 jetty 处理从 Eclipse 运行但未部署的请求

java - 根据父上下文记录到不同的文件

java - 检查断开的链接

java - 如何让我的 CountLines 函数(在 Java 中)输出文件中的最后一个数字?

java - Eclipse 未知的java对象

java - 如何使用 GoogleIdToken 从 java 连接到 google 工作表

java - 将 DTO 转换为参数列表

java - 在Java中导入图像

java - Java 和 Android 通用的库