Results 1 to 2 of 2
Thread: Help with an array
- 11-23-2011, 08:36 PM #1
Member
- Join Date
- Nov 2011
- Posts
- 1
- Rep Power
- 0
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;
- 11-23-2011, 11:53 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Re: Help with an array
I'm getting an array out of bounds exception 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
-
convert byte array into char array
By kgkamaraj in forum New To JavaReplies: 4Last Post: 09-13-2011, 12:32 PM -
Display Array on another class after extracting from txt file and into array problem
By jonathan920 in forum NetBeansReplies: 0Last Post: 05-12-2011, 08:04 PM -
Variable of an object in an array compared to an element of another array?
By asmodean in forum New To JavaReplies: 23Last Post: 09-07-2010, 09:12 PM -
Trying to make an array list // inserting an element to middle of array
By javanew in forum New To JavaReplies: 2Last Post: 09-06-2010, 02:03 AM -
How to add an integer to a array element and the store that backinto an array.
By Hannguoi in forum New To JavaReplies: 1Last Post: 03-31-2009, 07:40 AM
Bookmarks