【问题标题】:(JAVA) Comparing a word entered by a user with another word contained in a text file(JAVA) 将用户输入的单词与文本文件中包含的另一个单词进行比较
【发布时间】:2023-03-30 13:08:02
【问题描述】:

我想验证我的文本文件是否已经包含用户在文本字段中输入的单词。当用户单击验证该单词是否已在文件中时,用户将输入另一个单词。如果该单词不在文件中,它将添加该单词。我文件的每一行都包含一个单词。我放 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);

            }   
        }

    }

【问题讨论】:

  • 你正在使用的文件的内容是什么,你的输入是什么,控制台吐出什么?
  • 你用扫描仪试过这个吗?我总是尽可能喜欢扫描仪。
  • 嗨,尼古拉斯。文本文件的每一行包含 1 个单词。用户在文本字段中输入一个单词,我想知道这个单词是否已经在文本文件中,如果没有,添加它。

标签: java file swing file-io awt


【解决方案1】:

您似乎调用了两次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 起作用,请务必致电 @987654325 @ on line 在测试之前,过滤掉任何空格:

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

【讨论】:

  • 另外值得指出的是,如果文件包含两行不是输入的单词,第一行将关闭BufferedWriter,第二行将抛出异常(导致while 循环终止),因为它将尝试写入已关闭的 BufferedWriter
  • 非常感谢您的帮助! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 2020-11-07
  • 1970-01-01
相关资源
最近更新 更多