(JAVA)将用户输入的单词与文本文件中包含的另一个单词进行比较
我想验证我的文本文件是否已包含用户在文本字段中输入的单词。当用户单击“验证”该单词是否已在文件中时,用户将输入另一个单词。如果该单词不在文件中,它将添加该单词。我的文件的每一行都包含一个单词。我输入 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);
}
}
}
I'd like to verify if my text file already contains a word entered by a user in a textfield. When the user clicks on Validate if the word is already in the file, the user will enter another word. If the word is not in the file, it will add the word. Each line of my file contains one word. I put System.out.println to see what is being printed and it always say that the word does not existe in the file, but it's not true... Can you tell me what's wrong?
Thanks.
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您正在调用
in.readLine()
两次,一次在while
循环中,另一次在条件条件中。这导致它跳过每隔一行。另外,您想使用String.contains
而不是字符串。 contentEquals
,因为您只是检查该行是否包含该单词。此外,您需要等到搜索完整个文件后才确定未找到该单词。所以试试这个:(我的示例中省略了异常处理)
编辑:我刚刚重新阅读了您的问题 - 如果每一行都包含一个单词,那么
等于
或equalsIgnoreCase< /code>
可以代替
contains
,确保调用修剪
< /a> 在测试之前,在line
上过滤掉任何空格:It looks like you're calling
in.readLine()
twice, once in thewhile
loop and again in the conditional. This is causing it to skip every other line. Also, you want to useString.contains
instead ofString.contentEquals
, since you're just checking to see if the line contains the word. Furthermore, you want to wait until the entire file has been searched before you decide the word wasn't found. So try this:(Exception handling omitted from my example)
EDIT: I just re-read your question - if every line contains exactly one word, then
equals
orequalsIgnoreCase
would work instead ofcontains
, making sure to calltrim
online
before testing it, to filter out any whitespace: