copelandtml
Baseband Member
- Messages
- 45
Code:
public class C_C_ShuffleCards
{
public static void main(String[] args)
{
//program name
System.out.println("The Cards Shuffler");
//What the program does
System.out.println("\nThis program creates a deck of 52 cards.");
System.out.println("The cards are represented by the values 1 to 52");
System.out.println("It then 'shuffles' the cards.");
//create array
int[] cardsArray = new int[52];
//fill array
for(int index = 1; index < cardsArray.length - 1; index++)
{
cardsArray[index] = (int) ((52-1+1) * Math.random() + 1);
}
//printout of array before being shuffled
System.out.println("\nThe contents of the array before shuffling...");
printArrayValues(cardsArray);
//shuffle cards
//use for loop to loop through array
for(int index = 1; index < cardsArray.length - 1; index++)
{
//generate random number
int randomNumber = (int) ((52-1+1) * Math.random() + 1);
//compare adjacent element values
if(cardsArray[index] != cardsArray[index + 1])
{
//call the swapArrayElements() method
swapArrayElements(cardsArray, index, randomNumber);
}//end if
}//end for loop
//print out of array after being shuffled
System.out.println("\n\nThe contents of the deck after shuffling...");
printArrayValues(cardsArray);
}//end main
/*
* Method Name: printArrayValues()
* Purpose: prints to the screen the values in an int array
* Accepts: an array of type int
* Returns: NOTHING! IT'S A VOID METHOD!
*/
public static void printArrayValues(int [] array)
{
//set up a for loop
for(int index = 0; index < array.length; index++)
{
//set up an if statement so that whenever the index is a multiple of 10 it does a line feed
if(index % 10 == 0)
{
System.out.println();//prints a blank line
}
System.out.print(array[index] +", ");
}//end for
}//end method
/*
* Method Name: swapArrayElements()
* Purpose: swaps the values between the two specified elements of an array of type int
* Accepts: one array of type int, and two int values which represent the index numbers of the two array elements involved in the swap.
* Returns: NOTHING! It's a void method.
* */
public static void swapArrayElements(int[]array, int index1, int index2)
{
//do the swap using a temp variable
int temp;//my empty glass
//do the swap
temp = array[index1];
array[index1] = array[index2];
//complete the swap
array[index2] = temp;
}//end method
}//end class
It will run fine in Eclipse every once and a while and other times it will error out with the following errors:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52
at C_C_ShuffleCards.swapArrayElements(C_C_ShuffleCards.java:92)
at C_C_ShuffleCards.main(C_C_ShuffleCards.java:44)