![](/img/trans.png)
[英]Java: How to check with a scanner to see if a file contains integers or words?
[英]How to check a text file to see if it contains a string?
我正在编写一个类,该类读取文本文件(dictionary.txt)的内容,并使用isValidWord方法,该方法返回true或false取决于用户输入的字母是否在文本文件中形成单词
用户输入的字母通过“ Tile”对象来实现(我已经编写了Tile类,该类具有返回字母的getLetter方法)。 因此,将Tile对象的ArrayList传递给isValidWord方法。
构造函数采用文件名的字符串(驱动程序将其传递给dictionary.txt)。 然后,构造函数将文件的内容读取到字符串ArrayList中。
isValidWord方法采用一个Tile对象的ArrayList。 每个平铺对象都包含一个字母,因此,我使用Tile类中的getLetter方法将每个平铺对象的字母附加到字符串中。
然后,我尝试通读文本文件dictionary.txt,并查看该文件是否包含前一部分的字符串。 如果是,则isValid设置为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;
}
我的问题是,无论如何,isValidWord始终返回false。 我已经测试了变量str(实际上是从tile对象形式打印字符串的字母),但是由于某种原因,if语句永远不会被满足
删除临时的isValid
变量; 即使该文件包含单词,除非您立即返回,否则下一次迭代会使该单词为false
(并且您不需要它)。 喜欢,
while (s.hasNextLine())
{
String line=s.nextLine();
if(line.contains(str))
{
return true;
}
}
return false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.