gpt4 book ai didi

java - (JAVA) 将用户输入的单词与文本文件中包含的另一个单词进行比较

转载 作者:行者123 更新时间:2023-11-29 07:18:44 26 4
gpt4 key购买 nike

我想验证我的文本文件是否已经包含用户在文本字段中输入的单词。如果该词已存在于文件中,当用户单击 Validate 时,用户将输入另一个词。如果该词不在文件中,它将添加该词。我文件的每一行都包含一个词。我将 System.out.println 放入 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 循环中,另一次是在条件语句中。这导致它跳过每一行。另外,您想使用 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();
}

(我的示例中省略了异常处理)

编辑: 我刚刚重新阅读了您的问题 - 如果每一行都包含一个单词,那么 equalsequalsIgnoreCase将代替 contains 工作,确保调用 trimline 测试之前,过滤掉任何空白:

if (line.trim().equalsIgnoreCase(str))
...

关于java - (JAVA) 将用户输入的单词与文本文件中包含的另一个单词进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7139849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com