3 回答

TA貢獻1829條經驗 獲得超4個贊
不清楚為什么取 的余數2會產生偶數。相反,生成范圍0為 to 的數字h / 2,然后將其結果乘以2。喜歡,
public int nextEven(int h){
int n = ThreadLocalRandom.current().nextInt(1 + (h / 2)); // 0 to (h / 2) inclusive
return n * 2; // n * 2 is even (or zero).
}

TA貢獻1772條經驗 獲得超6個贊
mod 運算符%將為您提供第一個值除以第二個值的余數。
value % 2
...如果value是偶數則返回 0 ,如果value是奇數則返回1 。
由于rand是對包含您的代碼的類的實例的引用,因此您具有無限遞歸。你真正需要的是這樣的:
public int nextEven(int h){
int evenRandomValue;
do {
evenRandomValue = (int)(Math.random() * (h + 1));
} while(evenRandomValue % 2 == 1);
return evenRandomValue;
}

TA貢獻1893條經驗 獲得超10個贊
這是使用流實現此目的的一種非常明確的方法:
List<Integer> myRandomInts = Random.ints(lower, upper + 1)
.filter(i -> i % 2 == 0)
.limit(5).boxed()
.collect(Collectors.toList());
這可以理解為“在給定的邊界之間生成無限的隨機數流,過濾掉賠率,取前 5 個,變成Integer對象,然后收集到一個列表中。”
添加回答
舉報