将文本文件中的行存储在Java数组中[重复]

问题描述 投票:0回答:1

我的程序返回索引超出范围错误。我有点困惑为什么会这样。我已经尝试了一些方法,并且想知道是否有人可以为我指明更好的方向?

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]);
        }       
    }
}

编译器返回错误

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)

这是我的books.txt文件,以供更多参考。

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

任何帮助将不胜感激。

java arrays error-handling file-read
1个回答
0
投票

您在while循环中有一个for循环...

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

while循环正在检查您的输入文件是否有下一行,但是for循环继续进行并读取20行。您只需要一个循环,因此您应该选择一种方法或另一种方法来控制读取的行数。

© www.soinside.com 2019 - 2024. All rights reserved.