0

My program is returning an Index out of bounds errors. I am a bit confused why this is happening. I have tried a few things and was wondering if anyone can point me in better direction any help will do.

public static void booknames() throws FileNotFoundException {
Scanner in = new Scanner(new File("books.txt"));
String []books;
books = new String[20]; 
    while (in.hasNextLine()) {
        for(int i = 0; i <= books.length; i++  ) {
            String line = in.nextLine();
            books[i] = line;    
            System.out.println("A[" + i + "]" + books[i]);
        }       
    }
}

The compiler returns the error of

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
    at assignment7bookrecommender.bookrecommender.booknames(bookrecommender.java:23)
    at assignment7bookrecommender.bookrecommender.main(bookrecommender.java:9)

Here is my books.txt file for more reference.

A Walk in the Woods
Salem's Lot
John Adams
Illustrated Guide to Snowboarding
Dracula
Your Mountain Bike and You: Why Does It Hurt to Sit?
1776
Dress Your Family in Corduroy and Denim
High Fidelity
Guns of August
Triathlete's Training Bible
Jaws
Schwarzenegger's Encyclopedia of Modern Bodybuilding
It
What's That?
Team of Rivals
No Ordinary Time: Franklin and Eleanor Roosevelt: The Home Front in World War II
Truman
Basic Fishing: A Beginner's Guide
Life and Times of the Thunderbolt Kid

Any help would be greatly appreciated.

1 Answers1

1

You have a for loop inside a while loop...

while (in.hasNextLine()) {
    for(int i = 0; i <= books.length; i++  ) {
        String line = in.nextLine();
        ...

The while loop is checking if your input file has a next line, but then your for loop goes ahead and reads 20 lines. (21 currently, but even if you fix that...) You only need one loop, so you should chose one method or the other to control how many lines you read.

Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842