gpt4 book ai didi

java - 如何无限地生成随机数,直到它符合Java中的条件?

转载 作者:行者123 更新时间:2023-12-01 16:20:46 26 4
gpt4 key购买 nike

您是否知道如何生成随机对象,直到对象不满足条件为止?

我尝试过这样的:

//Btw getTeam1() is a hashMap of Integer,Fighter (a type of objects that I use)
//randomIndex
Object randomName = this.getTeam1().keySet().toArray()[new Random().nextInt(this.getTeam1().keySet().toArray().length)];
while(this.getTeam1().get(randomName).dontVerifyMyConditionBlabla) {
randomName = this.getTeam1().keySet().toArray()[new Random().nextInt(this.getTeam1().keySet().toArray().length)];
}

但显然,听起来不太好。有什么建议吗?

最佳答案

尝试do-while循环

verifyMyCondition(){
//proccess and return true or false
}

do
{
randomName = this.getTeam1().keySet().toArray()[new Random().nextInt(this.getTeam1().keySet().toArray().length)];
}while(verifyMyConditionthis.getTeam1().get(randomName)))

关于java - 如何无限地生成随机数,直到它符合Java中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62288490/

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