I dont know what to call this tittle.
Hi i need some help. I have been using ++ or -- for example i++. The problem is i would like my values to get picked at random thru my array. using ++ or -- is to predictable with what im doing. What formula can i use to pick random arrays instead of ++ or -- that go up one or down one?
Re: I dont know what to call this tittle.
Well... I don't know if this would be of much use to you, but maybe you can change it to what you need??
(your array) = (int) (Math.random() * 10)
I'm very new so i'm not sure if you can change that to select a random number in your array if your array was 10 numbers long.
Hope this helps in some way, shape, or form!
Good luck
Re: I dont know what to call this tittle.
Quote:
Originally Posted by
miller4103
What formula can i use to pick random arrays instead of ++ or -- that go up one or down one?
If I'm correctly understanding your question, then you can use:
int index = (int)(Math.random() * 5);
Normally, Math.random() will select random numbers from 0 to as close to 1 as possible but not exactly 1, such as 0.9999999. When you explicitly cast it to an integer, the compiler would round to either 0 or 1. Multiplying it by some number enables you to specify the range of values that will be randomly selected from. Afterward, you can increase or decrease the value by 1 using ++ or --. You should be careful though because you may run into ArrayIndexOutOfBoundsException.
Ideally, if you just wanted to get values out of your array in the order they were entered, consider using a for-loop, such as:
Code Java:
for(int i = 0; i < myArray.length; i++) {
// some code
}
Re: I dont know what to call this tittle.