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

    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];
    foodName [mSub] =;
    maxSub = mSub;

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

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    New Zealand
    Rep Power

    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);
        System.out.println("    accessing array at index " + mSub);
        foodName [mSub] =;

Similar Threads

  1. convert byte array into char array
    By kgkamaraj in forum New To Java
    Replies: 4
    Last Post: 09-13-2011, 12:32 PM
  2. Replies: 0
    Last Post: 05-12-2011, 08:04 PM
  3. Replies: 23
    Last Post: 09-07-2010, 09:12 PM
  4. Replies: 2
    Last Post: 09-06-2010, 02:03 AM
  5. Replies: 1
    Last Post: 03-31-2009, 07: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