在对象构造函数

时间:2017-05-14 00:55:26

标签: java random

如何在我的战斗机构造函数中使用随机数?我想让它向我展示这一个对象的3个随机参数。

    Fighter Lucas = new Fighter (2, 4, 7);
早些时候我用3种不同的方法随机做了这个:

    Random rand = new Random ();

     public int m = rand.nextInt(9) + 1;

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,其中包含在19(包括)范围内生成的三个随机数。