开发者

(JAVA) Comparing a word entered by a user with another word contained in a text file

I'd like to verify if my text file already contains a word entered by a user in a textfield. Whe开发者_JS百科n 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);

            }   
        }

    }


It looks like you're calling in.readLine() twice, once in the while loop and again in the conditional. This is causing it to skip every other line. Also, you want to use String.contains instead of String.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:

//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();
}

(Exception handling omitted from my example)

EDIT: I just re-read your question - if every line contains exactly one word, then equals or equalsIgnoreCase would work instead of contains, making sure to call trim on line before testing it, to filter out any whitespace:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜