【发布时间】: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 <= books.length; i++)是你的问题。一个大小为 20 的数组从 a[0] 到 a[19]。 -
准确来说应该是
for(int i = 0; i < books.length; i++)。 -
有道理。一旦程序完成读取,它就会以找不到任何行结束。
标签: java arrays error-handling file-read