Skip to content
Advertisement

Java Contain method cannot find symbol

I am trying to only print strings containing the word “The” from a text file but the contain method does not seem to be working. Is there any other way to do this or fix the contain method?

import java.util.*;
import java.io.*;
public class FileNerd
{
public static void main(String args[]) throws IOException 
{
    Scanner alpha = new Scanner(new File("E:\temp_Larry\NerdData.txt."));
    
    int maxIndx = -1;
    String text[] = new String[100];
    
    while(alpha.hasNext())
    {
        text[++maxIndx]=alpha.nextLine();
    }
    alpha.close();
    if(alpha.contains("The"))
    {
        System.out.println(alpha);
    } 
}   

}

Advertisement

Answer

You’re calling contains on Scanner object, you should call it on the lines that you read from file, that’s the whole point of reading them, right? Iterate through lines and call contains on those lines like this:

for (int i = 0; i< maxIndx; i++) {
  // Do whatever with text lines
  System.out.println(text[i].contains("The"));
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement