I’m trying to store data from an input file into a series of objects, which are then stored in an array. The issue is that it’s giving me an error message saying my array is out of bounds.
It gets the data from the file with no issues, but I don’t know why.
Here’s what I’ve got:
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(new File("input.txt"));
Scanner keyboard = new Scanner(System.in);
int numItems = scan.nextInt();
scan.nextLine();
Books bookObject[] = new Books[numItems];
Periodicals periodicalObject[] = new Periodicals[numItems];
for(int i = 0; i < numItems; i++)
{
String tempString = scan.nextLine();
String[] tempArray = tempString.split(",");
if(tempArray[0].equals("B"))
{
char temp = 'B';
//THIS IS WHERE THE IDE SAYS THE ERROR IS
bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);
}
else if(tempArray[0].equals("P"))
{
char temp = 'P';
periodicalObject[i] = new Periodicals(temp, tempArray[1], tempArray[2], tempArray[3], tempArray[4], tempArray[5]);
}
}
}
Here’s the input:
4
B,C124.S17,The Cat in the Hat,Dr. Seuss,Children’s Literature
P,QJ072.C23.37.4,Computational Linguistics,37,4,Computational Linguistics
P,QJ015.C42.55.2,Communications of the ACM,55,2,Computer Science
B,F380.M1,A Game of Thrones,George R. R. Martin,Fantasy Literature
Consider this line –
B,C124.S17,The Cat in the Hat,Dr. Seuss,Children’s Literature
This will be stored in tempString. When you do
for this, then
tempArray[0] -> B
tempArray[1] -> C124.S17
tempArray[2] -> The Cat in the Hat
tempArray[3] -> Dr. Seuss
tempArray[4] -> Children’s Literature
There is no tempArray[5]!
Therefore, when you say
it will throw an ArrayIndexOutOfBoundsException, because the maximum array index for tempArray is 4 and not 5.