joedoe
joedoe

Reputation: 49

Using random number in an object constructor

How do I use a random number in my Fighter constructor? I want it to show me 3 random parameters from this one object.

    Fighter Lucas = new Fighter (2, 4, 7);

earlier i made this random for 3 different methods:

    Random rand = new Random ();

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

Upvotes: 0

Views: 2998

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Pretty much as you have shown, you call rand.nextInt(max) + min either seperately or inline. It's better to follow Java naming conventions (Lucas looks like a class name), so something like

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);

or inline like

Fighter example2 = new Fighter(rand.nextInt(9) + 1, rand.nextInt(9) + 1, 
        rand.nextInt(9) + 1);

Both examples will construct a Fighter with three random numbers generated in the range 1 to 9 (inclusive).

Upvotes: 1

Related Questions