initialise var

How can i initialise an integer variable to be 1-10?
jtcyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
>>
would this work?

int ballToGoal = (int) (Math.random () * 10) ;
>>

Almost, but it would produce 0 - 9. You need



int ballToGoal = 1 + (int) (Math.random () * 10) ;
0
 
b612_foreverCommented:
java.util.Random rand = new java.util.Random();
int i = rand.nextInt(11);

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

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


;JOOP!
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
jtcyAuthor Commented:
would this work?

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

;JOOP!
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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).
0
 
sciuriwareCommented:
Like I said.

;JOOP!
0
 
CEHJCommented:
Yes - missed that. But it's better if he has the right code
0
All Courses

From novice to tech pro — start learning today.