I am trying to learn about searching for certain keywords for a project I am attempting. I am using a program created by someone else and I have tried to modify it to accept two arguments. I have so far attempted to add args[1] after the “Searching for ” + args[0] in hope that it would search for the second argument however this has not worked and lead to the program reporting that the position was found at -1 of line 2. The text file I am reading from displays as:
one
two
three
Can anyone provide help to how I can pass in two arguments.
Thank you
// 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());
}
}
}
I said in comments where the searching is done. I think you can copy most of that and do that again for args[1].
For more arguments (not sure if it’s the best/fastest solution):
I’m not sure if this works, probably not, but I wrote this just out of my head (not tested).