Write a Java program to shuffle a given array of integers.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class App {
/** Main Method */
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in); // Create a Scanner
System.out.print("Enter the number of elements: ");
int size = keyBoard.nextInt();
int numbers[] = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter the value of item number " + (i + 1) + ": ");
numbers[i] = keyBoard.nextInt();
}
Random rand = new Random();
for (int i = 0; i < numbers.length; i++) {
int randomIndexToSwap = rand.nextInt(numbers.length);
int temp = numbers[randomIndexToSwap];
numbers[randomIndexToSwap] = numbers[i];
numbers[i] = temp;
}
System.out.println(Arrays.toString(numbers));
keyBoard.close();
}
}
Comments
Leave a comment