【问题标题】:Storing lines from a text file within a java array [duplicate]在java数组中存储文本文件中的行[重复]
【发布时间】:2019-10-16 16:48:42
【问题描述】:

我的程序返回一个索引越界错误。我有点困惑为什么会这样。我尝试了一些事情,想知道是否有人可以为我指明更好的方向,任何帮助都可以。

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

任何帮助将不胜感激。

【问题讨论】:

  • for(int i = 0; i &lt;= books.length; i++) 是你的问题。一个大小为 20 的数组从 a[0] 到 a[19]。
  • 准确来说应该是for(int i = 0; i &lt; books.length; i++)
  • 有道理。一旦程序完成读取,它就会以找不到任何行结束。

标签: java arrays error-handling file-read


【解决方案1】:

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

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

while 循环正在检查您的输入文件是否有下一行,但随后您的 for 循环继续执行并读取 20 行。 (目前有 21 个,但即使你修复了它......)你只需要一个循环,所以你应该选择一种方法或另一种方法来控制你阅读的行数。

【讨论】:

  • 谢谢;感谢您的帮助
猜你喜欢
  • 2019-02-23
  • 2019-11-11
  • 2013-11-19
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 2023-03-14
  • 2015-03-21
相关资源
最近更新 更多