Results 1 to 2 of 2
  1. #1
    Marcus is offline Member
    Join Date
    Jun 2007
    Posts
    92
    Rep Power
    0

    Default java.lang.ArrayIndexOutOfBoundsException

    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:

    Java Code:
    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.
    Java 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
    I am using eclipse, if that is of any help? Thanks

    Marcus:cool:

  2. #2
    Felissa is offline Member
    Join Date
    Jun 2007
    Posts
    95
    Rep Power
    0

    Default

    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.
    Java 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. 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.

    Greetings
    Felissa:p

Similar Threads

  1. Replies: 8
    Last Post: 03-05-2011, 04:53 AM
  2. java.lang.ArrayIndexOutOfBoundsException
    By riccian in forum New To Java
    Replies: 0
    Last Post: 03-18-2008, 10:38 AM
  3. java.lang.ArrayIndexOutOfBoundsException
    By mew in forum New To Java
    Replies: 2
    Last Post: 12-02-2007, 10:40 PM
  4. Replies: 1
    Last Post: 08-01-2007, 12:47 AM
  5. Replies: 1
    Last Post: 07-25-2007, 11:55 PM

Posting Permissions

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