如何在Java中随机生成一个indefenitly直到它尊重一个条件?

问题描述 投票:0回答:1

Do you have an idea how to generate a random Object until an object doesn't respect a condition ?

我试过像这样。

//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)];
}

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

java random conditional-statements generate
1个回答
0
投票

试试 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)))
© www.soinside.com 2019 - 2024. All rights reserved.