简体   繁体   中英

How to count the amount of times a string appears in csv file?

I want to count the amount of times a certain word comes up in a CSV file, my code isnt working and unfortunately for some reason my debug wont work in eclipse so its hard to tell whats happening. I'm probably going about this wrong but if anyone has experience I would appreciate anyones input. this is how ive been trying to get it to work.

FileReader po = new FileReader("filename");
            Scanner underinvscan = new Scanner(po);
            
            
            for (int i = 0; i < file.size(); i++) {
                String string = file.get(i).LOC;
                if (!(string.contains("Under investigation"))) {
                    int count = 0; count++;
                
                    System.out.println("there have been" + count + "under investigations");
                
            
                    }
                }
            }
        
    }

You need to move the counter outside of the loop, so it is not reset in every loop:

        int count = 0; 
        for (int i = 0; i < file.size(); i++) {
            String string = file.get(i).LOC;
            if (!(string.contains("Under investigation"))) {
                count++;
            }
        }
        System.out.println("there have been" + count + "under investigations");

And possible the condition? If you want to count the strings that contain the "Under investigation" you need to remove the ! from the condition, currently you are counting the strings that do not contain the "Under investigation".

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