Results 1 to 2 of 2
  1. #1
    Helios00 is offline Member
    Join Date
    Nov 2011
    Posts
    1
    Rep Power
    0

    Default Help with an array

    Hey, I'm trying to read string and integer info from a input txt file into an array. The string is the description of the food and the integer is how many are in stock in inventory.

    I followed the example my teacher gave me but I'm getting an array out of bounds exception error for the bolded code line. It compiles everything alright but when I run it the error comes up. Any help would be appreciated, thanks.

    Scanner inMenu = new Scanner (new FileReader("Menu.txt")); //assigns scanner to input file

    //array for food description
    int mSub = 0;
    int maxSub = 0;
    String [] foodName = new String [maxSub];
    while(inMenu.hasNext())
    {
    foodName [mSub] = inMenu.next();
    mSub++;
    }
    maxSub = mSub;

    //array for food inventory
    int mSub2 = 0;
    int maxSub2 = 0;
    int [] foodInv = new int [maxSub2];
    while(inMenu.hasNextInt())
    {
    foodInv [mSub2] = inMenu.nextInt();
    mSub2++;
    }
    maxSub2 = mSub2;

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help with an array

    I'm getting an array out of bounds exception error
    There are two reasons why you can get that error:

    * first, the index may be too big (bigger than the size of the array)
    * and secondly, the index may be negative (which would be silly, but it happens!).

    By index I mean mSub, the thing in square brackets. That index must be between zero and the length of the array minus 1. (Make sure you understand why it is length-1)

    To decide which of the two is happening in your case you should use println() to see the values involved:

    Java Code:
    System.out.println("About to enter while loop");
    System.out.println("array length is " + foodName.length);
    while(inMenu.hasNext())
    {
        System.out.println("    accessing array at index " + mSub);
        foodName [mSub] = inMenu.next();
        mSub++;
    }

Similar Threads

  1. convert byte array into char array
    By kgkamaraj in forum New To Java
    Replies: 4
    Last Post: 09-13-2011, 11:32 AM
  2. Replies: 0
    Last Post: 05-12-2011, 07:04 PM
  3. Replies: 23
    Last Post: 09-07-2010, 08:12 PM
  4. Replies: 2
    Last Post: 09-06-2010, 01:03 AM
  5. Replies: 1
    Last Post: 03-31-2009, 06:40 AM

Posting Permissions

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