![](/img/trans.png)
[英]Comparing each word from a sentence entered by user with another text (android/java)
[英](JAVA) Comparing a word entered by a user with another word contained in a text file
我想验证我的文本文件是否已经包含用户在文本字段中输入的单词。 当用户单击验证是否单词已存在于文件中时,用户将输入另一个单词。 如果单词不在文件中,它将添加单词。 我文件的每一行都包含一个单词。 我放了System.out.println来查看正在打印的内容,它总是说该文件中不存在该单词,但这不是真的。
谢谢。
class ActionCF implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
str = v[0].getText();
BufferedWriter out;
BufferedReader in;
String line;
try
{
out = new BufferedWriter(new FileWriter("D:/File.txt",true));
in = new BufferedReader(new FileReader("D:/File.txt"));
while (( line = in.readLine()) != null)
{
if ((in.readLine()).contentEquals(str))
{
System.out.println("Yes");
}
else {
System.out.println("No");
out.newLine();
out.write(str);
out.close();
}
}
}
catch(IOException t)
{
System.out.println("There was a problem:" + t);
}
}
}
好像您在两次调用in.readLine()
,一次是在while
循环中, in.readLine()
一次是在条件中。 这导致它跳过每隔一行。 另外,您还想使用String.contains
而不是String.contentEquals
,因为您只是在检查该行是否包含单词。 此外,您要等到搜索到整个文件后再决定找不到该词。 所以试试这个:
//try to find the word
BufferedReader in = new BufferedReader(new FileReader("D:/File.txt"));
boolean found = false;
while (( line = in.readLine()) != null)
{
if (line.contains(str))
{
found = true;
break; //break out of loop now
}
}
in.close();
//if word was found:
if (found)
{
System.out.println("Yes");
}
//otherwise:
else
{
System.out.println("No");
//wait until it's necessary to use an output stream
BufferedWriter out = new BufferedWriter(new FileWriter("D:/File.txt",true));
out.newLine();
out.write(str);
out.close();
}
(示例中省略了异常处理)
编辑:我只是重新阅读您的问题-如果每一行equalsIgnoreCase
包含一个单词,那么equals
或equalsIgnoreCase
可以代替contains
起作用,请确保在测试它之前line
上调用trim
,以过滤掉任何空白:
if (line.trim().equalsIgnoreCase(str))
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.