[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
Solved

# initialise var

Posted on 2004-04-19
Medium Priority
198 Views
How can i initialise an integer variable to be 1-10?
0
Question by:jtcy
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 1

Expert Comment

ID: 10865603
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

LVL 24

Expert Comment

ID: 10865629
No, that delivers 0 - 10, correct is:

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

;JOOP!
0

Author Comment

ID: 10865666
would this work?

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

LVL 24

Expert Comment

ID: 10865684
No jtcy, that produces 0 - 9

;JOOP!
0

LVL 30

Expert Comment

ID: 10866063
>> 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

LVL 86

Accepted Solution

CEHJ earned 80 total points
ID: 10866686
>>
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

LVL 24

Expert Comment

ID: 10871376
Like I said.

;JOOP!
0

LVL 86

Expert Comment

ID: 10871403
Yes - missed that. But it's better if he has the right code
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
###### Suggested Courses
Course of the Month13 days, 23 hours left to enroll