Answer to Question #309546 in Java | JSP | JSF for Kyle

Question #309546

Write a Java program to shuffle a given array of integers.


1
Expert's answer
2022-03-15T12:46:02-0400


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();
	}


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS