/**
* @return random damage from monster
* @param monster of class Monster
*/
public int getRandomDamage(Monster monster) {
int min = monster.getMinDamage(); //this is set to 20 for monsters
int max = monster.getMaxDamage(); //this is set to 30 for monsters
return randomGenerator.nextInt(max - min + 1) + min;
}
这个 return 语句不起作用,因为它总是返回整数 20。任何解决问题的技巧,它都应该返回 20(int min) 和 30(int max) 之间的随机数。感谢您的帮助。
经过一番解决后发现 getMaxDamage();返回 20 而不是 30,现在运行良好,你这个愚蠢的打字错误。
最佳答案
发布的代码是 a valid and accepted approach (尽管如此,请重复使用相同的 PRNG...)。
我能想到的对该行为最合理的解释是,这些值不是预期的。例如,下面的结果总是 20。
int min = 20;
int max = 20;
return randomGenerator.nextInt(max - min + 1) + min;
替换这些值会产生 nextInt(1) + 20
,其中 nextInt(1)
始终返回 0,如 Random.nextInt(n)返回 [0,n)
范围内的整数。
其他一些原因..(调试是关于发展和测试假设)
也许,randomGenerator
不是Random
,而是 just broken .
class FairRandom {
public int nextInt(int n) {
return 0; /* chosen by fair dice roll */ }
}
}
或者,也许,随机数正在正确生成,并且“始终为 20”值来自其他地方。
或者,也许,随机数生成器在每次调用 nextInt
之前重新播种,而您非常不幸种子结果是“随机”选择 20 个。
或者,也许,你正在听@JasonC 的讲话,并对我的所有假设造成严重破坏;-)
关于java - 返回两个整数之间的随机数 - 始终相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22337318/