java - 即使条件为假也执行 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));
打印错误,如果执行,我得到一个错误的随机数
解决方案
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 - 将自定义项目添加到 Android 共享表?
- python - 如何使用 for 循环将各种 csv 文件读入数据帧并将其全部附加在一起
- sql - 用逗号替换点 SQL
- python - 使用 Elastichsearch Python 客户端时出现 ConnectionError
- typescript - 如何循环一个对象并将键和值推入另一个对象
- c# - 使用Regex从C#中的一个表中获取3条信息
- javascript - 在同一数组中组合来自不同对象的值 - javascript
- r - 如何修改 ggplot2 图例键?
- javascript - 如果用户不与页面交互,onbeforeunload 方法将不起作用
- c# - ImageMagick (Magick.NET) 的 Pdf 到 Jpg/Tiff 操作给我错误的颜色 CMYK 到 CMYK