Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2007
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Array Index Out Of Bounds Exception error

    Hello,

    I am writing a program that plays 1000 games of craps then prints out win, loss, the amt of rolls for each game, the odds of winning and losing. I am getting the following error:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 22
    at chapt7.Craps.play(Craps.java:94)
    at chapt7.Craps.main(Craps.java:17)

    I have been over this numerous times and can't seem to figure out the issue, here is my code.

    Code:
    package chapt7;
    
    // Craps class simulates the dice game craps.
    import java.util.Random;
    
    public class Craps 
    {
    	public static void main(String[] args)
    	{
    		int whenWin[] = new int[22]; //array to store number of rolls that it takes to win each game
    		 							 //whenWin[0] not used, more than 20 rolls counts is stored in whenWin[21]
    		int whenLose[] = new int[22]; //array to store number of rolls that it takes to lose each game
    									  //whenLose[0] not used, more than 20 rolls counts is stored in whenLose[21]
    		
    		//plays 1000 games of craps
    		for (int i = 0; i < 1000; i++)
    			play(whenWin, whenLose);
    		//1000 games complete
    		
    		//prints out the amount of times game was won on the 'j'th roll
    		for (int j = 1; j < 22; j++)
    		{
    			if (j == 21)
    				System.out.printf("The amount of times won after roll %d is %d\n", j, whenWin[j]);
    			else
    				System.out.printf("The amount of times won on roll %d is %d\n", j, whenWin[j]);
    		} //end for loop
    		
    		//prints out the amount of times game was lost on the 'j'th roll
    		for (int j = 1; j < 22; j++)
    		{
    			if (j == 21)
    				System.out.printf("The amount of times lost after roll %d is %d\n", j, whenLose[j]);
    		
    			else
    				System.out.printf("The amount of times lost on roll %d is %d\n", j, whenLose[j]);
    		} //end for loop
    		
    		chances(whenWin, whenLose); //caculates and prints out craps chances
    		avgLengthGame(whenWin, whenLose); //calculates and prints out avg number of rolls/game
    		
    	}//end main
    	
    	
    	// create random number generator for use in method rollDice
    	private static Random randomNumbers = new Random(); 
      
    	// enumeration with constants that represent the game status
    	private enum Status { CONTINUE, WON, LOST };                
      
    	// constants that represent common rolls of the dice
    	private final static int SNAKE_EYES = 2;
    	private final static int TREY = 3;      
    	private final static int SEVEN = 7;     
    	private final static int YO_LEVEN = 11; 
    	private final static int BOX_CARS = 12; 
      
    	// plays one game of craps
    	public static void play(int[] whenWin, int[] whenLose)
    	{
    		int myPoint = 0; // point if no win or loss on first roll
    		Status gameStatus; // can contain CONTINUE, WON or LOST
            int rollCount = 1; //counts # of rolls
            int sumOfDice = rollDice(); // first roll of the dice
            // determine game status and point based on first roll 
            switch ( sumOfDice ) 
            {
               case SEVEN: // win with 7 on first roll    
               case YO_LEVEN: // win with 11 on first roll
            	   gameStatus = Status.WON;
            	   whenWin[rollCount]++;
            	   break;
               case SNAKE_EYES: // lose with 2 on first roll
               case TREY: // lose with 3 on first roll      
               case BOX_CARS: // lose with 12 on first roll 
                  gameStatus = Status.LOST;
                  whenLose[rollCount]++;
                  break;
               default: // did not win or lose, so remember point
                  gameStatus = Status.CONTINUE; // game is not over
                  myPoint = sumOfDice; // remember the point
                  break; // optional at end of switch
            } // end switch 
      
            // while game is not complete
            while ( gameStatus == Status.CONTINUE ) // not WON or LOST
            { 
               sumOfDice = rollDice(); // roll dice again
               rollCount++;
               // determine game status
               if ( sumOfDice == myPoint ) // win by making point
               {
            	   		gameStatus = Status.WON;
            	   		whenWin[rollCount]++;
               }
               else
               {   
                  if ( sumOfDice == SEVEN ) // lose by rolling 7 before point
                  {	  
                	  	gameStatus = Status.LOST;
                  		whenLose[rollCount]++;
                  }
               }
            } // end while 
      
         } // end method play
      
         // roll dice, calculate sum and display results
         public static int rollDice()
         {
            // pick random die values
            int die1 = 1 + randomNumbers.nextInt( 6 ); // first die roll
            int die2 = 1 + randomNumbers.nextInt( 6 ); // second die roll
      
            int sum = die1 + die2; // sum of die values
            
            return sum; // return sum of dice
         } // end method rollDice
         
         //determines chances of wining craps
         public static int chances(int[] win, int[] lose)
         {
        	 int w = 0; //counts the number games won
        	 int l = 0; //counts the number games lost
        	 for (int i =1; i < 22; i++)
        	 {
        		 w = w + win[i];
        		 l = l + lose[l];
        	 }
        	 System.out.printf("The Chances of winning craps is %d:%d\n", w/w, l/w);
        	 return 0;	 
         }//end method chances
         
         //calculates the average length of each game, i.e. avg amt of rolls to win or lose
         public static int avgLengthGame(int[] win, int[] lose)
         {
        	 int numOfRolls = 0;
        	 int avg = 0;
        	 for (int i =1; i < 22; i++)
        	 {
        		 numOfRolls = numOfRolls + (win[i] * i) + (lose[i] * i);
        	 }
        	 avg = numOfRolls/1000;
        	 System.out.printf("The Average number of rolls per game is %d\n", avg);
        	 return 0;
         }//end method avgLengthGame
         
      } // end class Craps
    This is my first class in Java, as you can tell. I am using eclipse, if that is of any help. Any and all input is greatly appreciated. I thank you in advance.

  • #2
    Regular Coder Aradon's Avatar
    Join Date
    Jun 2005
    Location
    USA
    Posts
    734
    Thanks
    0
    Thanked 20 Times in 19 Posts
    You're problem is that you limit to the number of plays to 22. But it is very possible for you to play more then 22 times. If you notice, sometimes you'll get the exception and sometimes you wont.

    Code:
    int whenWin[] = new int[22]
    You can do one of three things. You can either increase the amount of the array to some extreme amount that makes no sense. You can keep it at 22 length, but while you're going through your loop, check for the length and either stop playing or increase the size of the array (by creating a new array with the same elements but an array of bigger size). Or you can use an ArrayList, which will only give you size issues if you take up the amount of RAM in your computer.

    My personal suggestion is to use an ArrayList.

    API of ArrayList

    Sample Use of an ArrayList
    ample Example 2

    You can do anything in arrayList that you can do in an Array. You are just switching from a direct representation to a class representation.
    "To iterate is human, to recurse divine." -L. Peter Deutsch

  • #3
    New to the CF scene
    Join Date
    Apr 2007
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you very much. I took your first idea but slightly changed it, I let the 'shooter' continue shooting until he won or lost but stopped counting the rolls, that way I could find out if he won or lost.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •