简体   繁体   中英

How to check a text file to see if it contains a string?

I'm writing a class that reads contents of a text file (dictionary.txt) and uses a method, isValidWord, that returns true or false depending on if letters entered by the user formulate a word in the text file

The letters entered by the user come via "Tile" objects (I've written the Tile class, which has a getLetter method that returns the letter). So, an ArrayList of Tile objects are passed to the isValidWord method.

The constructor takes a String of a file name (the driver program passes it dictionary.txt). The constructor then reads the contents of the file into an ArrayList of strings.

The isValidWord method takes an ArrayList of Tile objects. Each tile object contains a letter, so I use the getLetter method from the Tile class to obtain the letter of each tile object while appending it to a string.

I then attempt to read through the text file, dictionary.txt, and see if the file contains the string from the previous part; if it does, isValid is set to true.

private boolean isValid;
private String str;
private ArrayList<String> list = new ArrayList<String>();

public Dictionary(String fileName) throws IOException
{

      File file = new File(fileName);
      Scanner s = new Scanner(file);
      while (s.hasNextLine())
      {
         list.add(s.nextLine());
      }
      str = "";
      isValid = true;
}

public boolean isValidWord(ArrayList<Tile> tiles) throws IOException
{     

      StringBuilder sb = new StringBuilder(); 
      for(int i=0; i< tiles.size(); i++)
      {
         sb.append(tiles.get(i).getLetter());
      } 

      str = sb.toString();  

      File file = new File("dictionary.txt");
      Scanner s = new Scanner(file);

      while (s.hasNextLine())
      {

         String line=s.nextLine();

         if(line.contains(str))
         {
            isValid = true;
         }
         else
            isValid = false;
      }   

      return isValid;
}

My problem is that no matter what, isValidWord is always returning false. I've tested the variable str (which indeed prints the string the letters from the tile objects form) but for some reason, the if statement is never being satisfied

Remove the temporary isValid variable; even if the file contains the word unless you return immediately your next iteration makes that false (and you don't need it). Like,

while (s.hasNextLine())
{
    String line=s.nextLine();
    if(line.contains(str))
    {
        return true;
    }
}   
return false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM