Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

initialise var

How can i initialise an integer variable to be 1-10?
0
jtcy
Asked:
jtcy
1 Solution
 
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
 
jtcyAuthor Commented:
would this work?

int ballToGoal = (int) (Math.random () * 10) ;
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
CEHJCommented:
>>
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
 
sciuriwareCommented:
Like I said.

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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now