【发布时间】:2016-04-18 15:16:34
【问题描述】:
当我运行代码时,它会报错
java.lang.ArrayIndexOutOfBoundsException: 0
at SearchFile.main(SearchFile.java:28)
MyNote.txt是保存在我电脑D目录下的文本文件。 而“ad”是该文本文件中的单词。
import java.io.*;
public class SearchFile {
public static void main(String args[]) {
args[0] = "ad";
if (args.length > 0) {
String searchword = args[0];
try {
int LineCount = 0;
String line = "";
BufferedReader bReader = new BufferedReader(new FileReader("D:/MyNote.txt"));
while ((line = bReader.readLine()) != null) {
LineCount++;
int posFound = line.indexOf(searchword);
if (posFound > - 1) {
System.out.println("Search word found at position " + posFound + " on line " + LineCount);
}
}
bReader.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
}
else {
System.out.println("Please provide a word to search the file for.");
}
}
}
我不知道错误是什么或我做错了什么。 我是新手,实际上请帮忙! 谢谢你
【问题讨论】:
-
您正在为 args[0] 分配一个值,而没有检查是否有这样的索引要设置。换句话说,如果没有给 main 方法提供参数,那么 args[0] 将抛出一个
ArrayIndexOutOfBoundsException,因为没有这样的数组索引。
标签: java search find text-files word