简体   繁体   中英

Counting the number of times a specific word appears in a txt file while using a try/catch block in java

My goal is to have the program run a count on the number of times the word 'secret' appears in the text document while ignoring words such as 'secretive' and 'secsecret'. I was able to get it to count, but it is only returning an occurrence of the word 2 times instead of the 4 times the word appears in the document and is including the 'secsecret' I added. Is there some kind of exception statement that can be added to keep it from picking up the 'secsecret' in the document? And I'm not sure what I did incorrectly for it to only pick up 2 occurrences of the word 'secret'. This is a lab assignment for my object-oriented programming class.

Here is what I have so far:

package lab4;

import java.util.Scanner;
import java.io.File;
import java.util.NoSuchElementException;
import java.io.FileNotFoundException;



public class Lab4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{

        String keyword = "secret";
        int c = 0;

        try
        {
            Scanner file = new Scanner(new File("/Users/Taba/Desktop/Lab4textdoc.txt"));
            while (file.hasNext())
            {
                 keyword = file.nextLine();
                if (! file.hasNextLine())
                {
                    System.out.println("Invalid file format");
                    String invalidData = file.nextLine();
                }
                else
                {
                    keyword = file.nextLine();
                    String newLine = file.nextLine();
                    c++;
                    System.out.println("The keyword " + keyword + " appears " + c + " times." );
                }
            }
                file.close();
        }

            catch(FileNotFoundException fnfe)
                {
                System.out.println("Unable to find Lab4textdoc.txt, exiting");
                }
            catch(NoSuchElementException nsee)
                {
                System.out.println("Attempt to read past the end of the file");
                }

    }

}

Here is what I have in the text document:

secret
secsecret
secretive
secret
Secret
secret

And this is the output it is giving me:

run:
The keyword secsecret appears 1 times.
The keyword Secret appears 2 times.
BUILD SUCCESSFUL (total time: 0 seconds)

You 1st problem is that you are overwriting the word you suppose to find here:

keyword = file.nextLine();

you need instead to declare another string object and compare that against the keyword.

On the other hand, you didn't specify if words must match sensitiveness, because in java a string " Secret " is not the same as " SECRET " or " secret "

for both options you will need equals or equalsIgnoreCase

Basically:

  • every time you call nextLine , you read the next line of the file. So you should call it just once per iteration (only in the beggining of the while loop). As you're calling more than once inside the loop, you're skipping lots of lines without taking a look at them
  • you're not really counting what you want. You should include an if (is the string I want) c++ . But you're incrementing c without testing anything, leading to wrong results

Your code should be something like:

while (file.hasNext()) {
    keyword = file.nextLine();
    if ("secret".equals(keyword)) {
        c++;
    }
}
System.out.println("The keyword " + keyword + " appears " + c + " times." );

If you want to count more words (like "Secret"), you should create a different counter for each one, and do a respective if for each case as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM