Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java数组中存储文本文件中的行_Java_Arrays_Error Handling_File Read - Fatal编程技术网

在java数组中存储文本文件中的行

在java数组中存储文本文件中的行,java,arrays,error-handling,file-read,Java,Arrays,Error Handling,File Read,我的程序正在返回索引越界错误。我有点困惑为什么会发生这种情况。我试过一些方法,想知道是否有人能为我指出更好的方向,任何帮助都可以 public static void booknames() throws FileNotFoundException { Scanner in = new Scanner(new File("books.txt")); String []books; books = new String[20]; while (in.hasNextLine()) {

我的程序正在返回索引越界错误。我有点困惑为什么会发生这种情况。我试过一些方法,想知道是否有人能为我指出更好的方向,任何帮助都可以

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]);
        }       
    }
}
这是我的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

任何帮助都将不胜感激。

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

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

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

forint i=0;精确地说,它应该是forint i=0;我知道书的长度;相反,我是++的,这很有意义。一旦程序完成阅读,它就结束了,找不到行;我感谢你的帮助
while (in.hasNextLine()) {
    for(int i = 0; i <= books.length; i++  ) {
        String line = in.nextLine();
        ...