首页 > 解决方案 > 即使条件为假也执行 if 语句

问题描述

我有一种生成随机数的方法,但我希望其中一些被丢弃。这是代码:

    public static int getRandomX(int max, int[] exclude){
        Random randomGenerator = new Random();
        Integer[] toExclude = Arrays.stream( exclude ).boxed().toArray(Integer[]::new);
        Integer random = Integer.valueOf(randomGenerator.nextInt(max));
        do{
            System.out.println(!Arrays.asList(toExclude).contains(random));
            if(!(Arrays.asList(toExclude).contains(random))){
                return random;
            } else{
                random ++;
            }
        }while(!Arrays.asList(toExclude).contains(random));
        return random;
    }   

即使System.out.println(!Arrays.asList(toExclude).contains(random));打印错误,如果执行,我得到一个错误的随机数

标签: java

解决方案


while 循环中有不正确的逻辑。只要有一个数字需要排除,您就需要执行循环,而不是相反。

只需您的代码即可:

public static int getRandomX(int max, int[] exclude) {
    Random randomGenerator = new Random();
    Integer[] toExclude = Arrays.stream(exclude).boxed().toArray(Integer[]::new);
    Integer random;
    do {
        random = Integer.valueOf(randomGenerator.nextInt(max));
    } while (Arrays.asList(toExclude).contains(random));
    return random;
}

推荐阅读