# Random Number 1/40 Chance

Discussion in 'Plugin Development' started by AstramG, Mar 10, 2013.

Not open for further replies.
1. Offline

### AstramG

How could I make something occur on a 1 out of 40 chance, I'm using this for dropping mob heads at a 2.5% chance and I can't figure out how to make this happen at this 1/40 chance.

#1
2. Offline

### TomTheDeveloper

AstramG
Create a random number generator that goes to 39 (because it starts from 0)
Then say:

Code:java
`if ("that random number" == 1){//do something}`

3. Offline

you could do a switch statement so it's not like if else if else if else if else if

#3
4. Offline

### molenzwiebel

Code:
```Random r = new Random();
int rand = r.nextInt(41);
if (rand == 33) {
Do stuff...
}
```
Rand will be a number between 0-40 (0 and 40 included). You can take any number, I just did 33

#4
5. Offline

### AstramG

Well, I understand the approach but I'm a bit confused on creating a random number generator, assistance in creating one would be nice

Ah, thank you, but just for understanding why is nextInt 41? Why not 40?

EDIT by Moderator: merged posts, please use the edit button instead of double posting.

Last edited by a moderator: May 31, 2016
#5
6. Offline

7. Offline

### molenzwiebel

AstramG look at my post
EDIT: nextInt will generate a number between 0 and arg-1. So nextInt(2) will give a number between 0 and 1 with 0 and 1 included

#7
8. Offline

### TomTheDeveloper

No if you want a 1/40 chance, just use 39 there, because a number generator goes from 0 to <a choosen number>, 0 included, so use 39

9. Offline

### Rprrr

TomTheDeveloper molenzwiebel
You're all wrong.
You use randomGenerator.nextInt(40). That generates 40 numbers. It starts at 0, it ends at 39.
So you don't use .nextInt(39), because it only gives 39 numbers, and you don't use .nextInt(41) either, because it gives 41 numbers.

#9
hapm likes this.
10. Offline

Clean and simple way:
Code:
```int n = 1 + (int)(Math.random() * 40);
if(n == 1){
//Do Stuff >:D
}```

11. Offline

### TomTheDeveloper

Rprrr
Oh, sorry then, I was wrong, sorry

Thx to correct me