我正在尝试了解如何为我正在尝试的项目搜索某些关键字。我正在使用由其他人创建的程序,并尝试对其进行修改以接受两个参数。到目前为止,我一直试图在“搜索”+ args[0] 之后添加 args[1],希望它会搜索第二个参数,但是这没有奏效,并导致程序报告该位置是在 -第 2 行的第 1 行。我正在读取的文本文件显示为:
one
two
three
任何人都可以为我如何传递两个参数提供帮助。
谢谢
// Import io so we can use file objects
import java.io.*;
public class searchfile {
public static void main(String args[]) {
try {
// Open the file c:\test.txt as a buffered reader
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/Sean/Desktop/Java/MyText.txt"));
// Start a line count and declare a string to hold our current line.
int linecount = 0;
String line;
// Let the user know what we are searching for
System.out.println("Searching for " + args[0] + " in file...");
// Loop through each line, stashing the line into our line variable.
while (( line = bf.readLine()) != null)
{
// Increment the count and find the index of the word
linecount++;
int indexfound = line.indexOf(args[0]);
// If greater than -1, means we found the word
if (indexfound > -1) {
System.out.println("Word was found at position " + indexfound +" on line " + linecount);
}
}
// Close the file after done searching
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}