I know this for normal integers, but is there for such a thing as indices?
Random dice = new Random();
int n = dice.nextInt(6);
System.out.println(n);
What do you mean? Array indices are normal numbers, so you can easily do
String names[] = { "One", "Two", "Three", "Four", "Five", "Six" };
Random Dice = new Random();
int n = Dice.nextInt(6);
System.out.println(names[n]);
Or do you mean a random Iterator class? Google is your friend here, this is the first hit I get.
Another solution would be:
int randomElement = yourArray[Math.random()*yourArray.length];
Math.random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.
For example: If Math.random() generated .2 and your array had a length of 10, you would get an index of 2.
Math.random return double? While the array would expect index to be int?Here is another possibility that worked for me in React js if you want to return the value of that index in an array.
const myArray = [1,2,5,7,6,87,45,34,23,12]
const rand = myArray[Math.floor(Math.random() * myArray.length)];
console.log('value of the index', rand);
console.log('index in the array',myArray.indexOf(rand));
function whosPaying(names)
{
var randomIndex = Math.floor(Math.random() * names.length);
// Generate a random index
var selectedName = names[randomIndex];
// Select the name at the random index
return selectedName + " is going to buy lunch today!";
}
// Example Input
var names = ["Angela", "Ben", "Jenny", "Michael", "Chloe"];
// Example Output
console.log(whosPaying(names));
Dicein your example is a variable and hence should be written lowercase according to the common Java style.