mardi 8 novembre 2016

Really basic Java Math.random() [duplicate]

This question already has an answer here:

So I'm doing a school project(but I'm forgetting some basic stuff) which I have to randomly pick an item from an Array, so I'm doing it by generating a random index, then I'll pull out that object and do something about it(but that's important, I'm confused with the random part)

Question 1:

So Math.random() generates [0,1), right?

Question 2:

So If I want a number from [0,5), that means, 0 1 2 3 4, I'll have:

int index = (int)(Math.random() * 5); Correct?

Question 3:

What if I want[0,5]? Is it int index = (int)(Math.random()*5 + 1)?

Question 4:

What if It's something that's not starting with zero?

What if It's [2,4]? What if It's [3,7)? See I'm confused how to do the application of this method.

Most importantly:

Say if I have an array of 25 objects, and I want to randomly pick one, that would be:

int randIndex = (int)(Array.length * Math.random()) ?

(This is easier because it starts with 0, please help with question 4).

Thank you for your time!




Aucun commentaire:

Enregistrer un commentaire