将文本文件中的行存储在 java 数组中
Storing lines from a text file within a java array
我的程序返回索引越界错误。我有点困惑为什么会这样。我已经尝试了一些事情,想知道是否有人可以指出我更好的方向,任何帮助都可以。
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]);
}
}
}
编译器returns错误
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
如有任何帮助,我们将不胜感激。
你在 while 循环中有一个 for 循环...
while (in.hasNextLine()) {
for(int i = 0; i <= books.length; i++ ) {
String line = in.nextLine();
...
while 循环正在检查您的输入文件是否有下一行,但是您的 for 循环继续读取 20 行。 (目前是 21,但即使你修复了...)你只需要一个循环,所以你应该选择一种方法或另一种方法来控制你读了多少行。
我的程序返回索引越界错误。我有点困惑为什么会这样。我已经尝试了一些事情,想知道是否有人可以指出我更好的方向,任何帮助都可以。
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]);
}
}
}
编译器returns错误
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
如有任何帮助,我们将不胜感激。
你在 while 循环中有一个 for 循环...
while (in.hasNextLine()) {
for(int i = 0; i <= books.length; i++ ) {
String line = in.nextLine();
...
while 循环正在检查您的输入文件是否有下一行,但是您的 for 循环继续读取 20 行。 (目前是 21,但即使你修复了...)你只需要一个循环,所以你应该选择一种方法或另一种方法来控制你读了多少行。