Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.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 blue j中搜索文本文件中的单词_Java_Search_Find_Text Files_Word - Fatal编程技术网

在java blue j中搜索文本文件中的单词

在java blue j中搜索文本文件中的单词,java,search,find,text-files,word,Java,Search,Find,Text Files,Word,当我运行代码时,它会给出一个错误 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] =

当我运行代码时,它会给出一个错误

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
,并且您的
args[0]=“ad”行失败


尝试使用参数启动应用程序,而不是尝试在代码中手动设置参数。如果您没有看到任何其他解决方案,请自己创建一个数组,并将其设置为填充了要使用的信息的变量。

使用另一个变量,而不是
args[0]

String str = "ad";
if (str.length() > 0) {
String searchword = str;

变量
args[0]
通过main方法作为类的输入。此外,在您的情况下,它是空的,因为没有给出任何参数。

您正在为args[0]赋值,而没有检查是否有这样的索引要设置。换句话说,如果没有给main方法提供任何参数,那么args[0]将抛出一个
ArrayIndexOutOfBoundsException
,因为没有这样的数组索引。非常感谢你,伙计,实际上你看到的代码不是我写的,这就是为什么我无法正确编辑代码的原因,这很有帮助:)是的,与别人的代码一起工作有时会很痛苦。你是一个大帮手。。嘿,我怎么才能把你当作朋友呢!!兄弟,我还有一件事要做。。