Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: I need help with ArrayIndexOutOfBounds exception!

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default I need help with ArrayIndexOutOfBounds exception!

    Hi all,

    I am writing a program for school, and am stuck. The program is throwing an ArrayIndexOutOfBounds exception, which I realize means that my array has an index that is less than zero, but I can't see how that's happening. Can you please look over my code and see if it's something obvious? The program generates a random number and then compares a user guess to that number and provides feedback regarding how close the guess is. The problem happens about halfway down at "engine.generateNewSecret()". When I run this method independently, it will create the array without a problem, but inside of the 'mother' program it throws the exception.

    Here you go:
    import java.util.Scanner;
     
    public class Bagel {
     
    	public static void main(String[] args) {
     
    		System.out.println("Welcome!"); // it's nice to be nice :)
     
    		Scanner keyboard = new Scanner(System.in);
    		Engine engine = new Engine(); // declare object instances for this class
    		Player player = new Player();
    		Validator validator = new Validator();
     
    		boolean reset = true; // menu switch
     
    		while (reset == true) {
     
    			System.out.println("\nEnter the number of digits to use: ");
    			engine.numDigits = keyboard.nextByte(); // gets the numDigits
     
     
    			System.out.println("\nEnter the player's name: ");
    			player.name = keyboard.next(); // gets the player's name
     
    			boolean play = true; // menu switch
     
    			while (play == true) {
    				for (int gameCount = 1; gameCount > 0; gameCount++) {
    					System.out.println("\n Starting game " + gameCount);
     
    					engine.generateNewSecret(); // [B]here's the problem![/B]
    					int numberOfGuesses = 0;
    					int newNumberOfGuesses;
    					while (true) {
    						newNumberOfGuesses = numberOfGuesses;
    						System.out.println("\nEnter guess: ");
    						player.askForGuess();
    						validator.validateGuess(engine.getSecret(),
    								player.guess, engine.getNumDigits());
    						if (validator.validateGuess(engine.getSecret(),
    								player.guess, engine.getNumDigits()) == false) 
    						{
    							numberOfGuesses++;
    							continue;
    						}
     
    						else
    							break;
    					}
    					gameCount++;
    					System.out.println("Congratulations! You won in "
    							+ numberOfGuesses + "moves!");
    					if (newNumberOfGuesses < numberOfGuesses)
    						player.fastestWin = newNumberOfGuesses;
    					else
    						player.fastestWin = numberOfGuesses;
    					System.out.println("\nStatistics for " + player.name + ":");
    					System.out.println("\nGames completed: " + gameCount);
    					System.out.println("\nNumber of digits: "
    							+ engine.getNumDigits());
    					System.out.println("\nFastest win: " + player.fastestWin);
    				}
    				System.out.println("p - Play again\nr - Reset game\nq - Quit");
    				System.out.println("\nWhat would you like to do?");
    				String menu = keyboard.nextLine().trim().toLowerCase().substring(0,1);
    				if (menu == "p")
    					play = true;
    				else if (menu == "r") {
    					play = false;
    					reset = true;
    				} else if (menu == "q")
    				{
    					System.out.println("/nGoodbye!");
    					System.exit(0);
     
     
    				}
     
     
    			}
     
    		}
     
    	}
     
    }

    Here's the code for the Engine class:

     
    import java.util.Random;
     
     
    public class Engine {
    	Random random = new Random();
    	byte numDigits;
    	byte[] secretNumber = new byte[numDigits];
     
     
     
     
     
    public void generateNewSecret()
    {
    	 int number = random.nextInt(((int)Math.pow(10, numDigits) - ((int)Math.pow(10, numDigits-1)))) + ((int)Math.pow(10, numDigits-1));
    	 int temp = numDigits;
    	 for (int i = 0; i < numDigits; i++)
    		{
     
    		    secretNumber[i] = (byte)((number/(Math.pow(10, temp-1))));  // [B]Exception here![/B]
    		    if (number<10)
    		    	break;
    			number = number%((int)(Math.pow(10, temp-1)));
     
    			temp--;
     
    		}
    }
     
    public byte getNumDigits()
    {
    	return numDigits;
    }
    public byte[] getSecret()
    {
    	return secretNumber;
    }
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
     
    	}
     
    }
    Last edited by jps; November 2nd, 2012 at 05:05 PM. Reason: fixed code tags


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: I need help with ArrayIndexOutOfBounds exception!

    Your Engine class has a numDigits field. What is the value of numDigits?

    Your Engine class creates an array of bytes named secretNumber. What is the size of that array?

    Your main() in Engine doesn't do anything. What do you mean by saying "When I run this method independently, it will create the array without a problem."

    Why not flesh out Engine.main() to create an Engine object and test generateNewSecret() for that object, and let us know how it goes?





    Cheers!

    Z

  3. The Following User Says Thank You to Zaphod_b For This Useful Post:

    jameschristian (November 3rd, 2012)

  4. #3
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: I need help with ArrayIndexOutOfBounds exception!

    The numDigits field is taken from user input. I have tested that and it is receiving it properly. What I mean by running the method independently is that when I do create an engine object inside the engine main(), and then call generateNewSecret(), no exception is thrown, and the array contains the values it should in the proper order. Only when I call the method from outside the class, in the bagel class I posted, does it do this. I have run tests on the array to see if the indexes are anything but what I expected them to be, but it always comes out 0,1,2,3 etc like it should. Do I need to create a constructor inside the engine class, maybe? If so, can you clue me in as to what this might look like? I am tearing my hair out here, and this thing is due Monday, so any help is, again, much appreciated.

  5. #4
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: I need help with ArrayIndexOutOfBounds exception!

    Also, the size of the array is numDigits. I assigned 4 to numDigits to test it with, and it all came out right in the engine main method, but again, when I call the method from outside the class, ArrayIndexOutOfBoundsException happens every time.

  6. #5
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: I need help with ArrayIndexOutOfBounds exception!

    Just in point of fact, I also had to cast the number going in to the array as an int before I cast it as a byte, which made the numbers all come out right, but that's not really related to the problem...

  7. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: I need help with ArrayIndexOutOfBounds exception!

    Quote Originally Posted by jameschristian View Post
    The numDigits field is taken from user input.
    Yes, but is this done before or after the array has been created? In other words, what is the value of numDigits when you create your secretNumber array? A quick look at your code will reveal the answer -- which is 0, and aways 0. So knowing this *where* should you be initializing the secretNumber array?

  8. The Following User Says Thank You to curmudgeon For This Useful Post:

    jameschristian (November 3rd, 2012)

  9. #7
    Junior Member
    Join Date
    Nov 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: I need help with ArrayIndexOutOfBounds exception!

    You rock. Seriously. There is rocking being done and you are doing it. Thank you!

Similar Threads

  1. Replies: 2
    Last Post: August 30th, 2012, 10:45 AM
  2. Exception
    By prabhakar in forum Exceptions
    Replies: 5
    Last Post: July 21st, 2012, 07:51 AM
  3. Replies: 5
    Last Post: September 5th, 2011, 11:31 AM
  4. Replies: 6
    Last Post: March 25th, 2011, 04:42 PM
  5. can someone please help me im getting exception
    By kristynrod in forum Exceptions
    Replies: 2
    Last Post: March 15th, 2011, 05:40 PM