gpt4 book ai didi

java - 即使条件为假也执行 if 语句

转载 作者:行者123 更新时间:2023-12-01 19:33:11 25 4
gpt4 key购买 nike

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

    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)); 打印 false if 被执行并且我得到错误的随机数

最佳答案

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;
}

关于java - 即使条件为假也执行 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com