如何在我的战斗机构造函数中使用随机数?我想让它向我展示这一个对象的3个随机参数。
Fighter Lucas = new Fighter (2, 4, 7);
早些时候我用3种不同的方法随机做了这个:
Random rand = new Random ();
public int m = rand.nextInt(9) + 1;
答案 0 :(得分:1)
就像你所展示的那样,你可以单独或内联地呼叫rand.nextInt(max) + min
。遵循Java命名约定(Lucas
看起来像一个类名称)更好,所以像
Random rand = new Random();
int a = rand.nextInt(9) + 1;
int b = rand.nextInt(9) + 1;
int c = rand.nextInt(9) + 1;
Fighter example1 = new Fighter(a, b, c);
或内嵌,如
Fighter example2 = new Fighter(rand.nextInt(9) + 1, rand.nextInt(9) + 1,
rand.nextInt(9) + 1);
这两个示例都将构建一个Fighter
,其中包含在1
到9
(包括)范围内生成的三个随机数。