I'm having a bit trouble with this assignment. I believe I already have the basis of the searching method covered, but there is an error in my code somewhere that makes it not work. You have to input the file via scanner method and are only allowed to search for the string via charAt() and length, no other methods in the String or String builder class are allowed.
I have to search the file for the word and report back the amount of times the word is found and which line number it is on.
Any help is appreciated, thanks.
public void FindWord(String fileName, String word)throws IOException
{
Scanner fileInput = new Scanner (new File(fileName));//scanner that reads the file
int lineCounter = 0; //declares the line
String line;
while (fileInput.hasNextLine())
{
line = fileInput.nextLine();
System.out.println(line);
lineCounter++;
outerloop: for (int i = 0; i <= line.length();i++)
{
for (int j = 0; j <= word.length();)
{
if (line.charAt(i) == word.charAt(j))
{
if (j == word.length())
{
amount++;
lineNumbers += (lineCounter + ", ");
continue outerloop;
}
j++;
i++;
}
else if (line.charAt(j) != word.charAt(j))
{
continue outerloop;
}
}
}
}
}
Edit: well, I did narrow it down to a specific problem. The code runs up until the if statement where I'm checking the string called "line" created by the input file against the string l entered called word. It produces an out of bounds error, with the number 4, but that confuses me because there's definitely more than 4 characters in the string called line. I can alter the if statement to produce real results without this error, but none of my variables have their values increased and remain at 0, still proving that my if statement doesn't work.
So basically, I needed help finding a solution to checking the characters in the line against the word input, only using the charAt() and length()methods
some java codevariablexhas valueybut I expectedz" Please visit the help center and also read How to Ask.