Saturday, November 11, 2017

Get Random numbers/value from the array in Java

package MyPackage;

import java.util.Random;

public class GenerateRandom {

public static void main(String[] args) {

// Create an aarray
final int numbers[] = { 11, 22, 33, 44, 55, 66 };

// Random Class
Random rand = new Random();

int number = rand.nextInt(6);

System.out.println(number);

System.out.println(numbers[number]);

}

}


-----------------------------------------------------------------------------------


package MyPackage;

import java.util.Random;

public class GenerateRandom {

public static void main(String[] args) {

// Create an aarray
final String name[] = { "Jack", "Stefen", "Alex", "Jeo", "Bill", "Jay" };

// Random Class
Random rand = new Random();

int number = rand.nextInt(6);

System.out.println("Index of the Array: " + number);

System.out.println("Random name form the Array: " + name[number]);

}

}

No comments:

Post a Comment