Link to home
Start Free TrialLog in
Avatar of jtcy
jtcy

asked on

initialise var

How can i initialise an integer variable to be 1-10?
Avatar of b612_forever
b612_forever

java.util.Random rand = new java.util.Random();
int i = rand.nextInt(11);

// the 11 means (10 + 1) beacuse the parameter 11 is exclusive.
No, that delivers 0 - 10, correct is:

    int i = rand.nextInt(10) + 1;


;JOOP!
Avatar of jtcy

ASKER

would this work?

int ballToGoal = (int) (Math.random () * 10) ;
No jtcy, that produces 0 - 9

;JOOP!
Avatar of Mayank S
>> int ballToGoal = (int) (Math.random () * 10) ;

int ballToGoal = ( int ) Math.round ( ( Math.random () * 10 ) ) ; could work. Or: int ballToGoal = ( int ) ( Math.random () * 11 ) ;

- because random () returns double values greater than or equal to 0.0 and lesser than 1.0. So when you take the ( int ) part of Math.random () * 10, it will always lesser than or equal to 9 (even 9.9 would be converted to 9, that way).
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Like I said.

;JOOP!
Yes - missed that. But it's better if he has the right code