Counting an Occurrence in an Array (Java)

后端 未结 12 1754
情歌与酒
情歌与酒 2020-12-16 05:23

I am completely stumped. I took a break for a few hours and I can\'t seem to figure this one out. It\'s upsetting!

I know that I need to check the current element in

12条回答
  •  隐瞒了意图╮
    2020-12-16 06:22

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
     // This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
    public class fileopen {
        public static void main(String[] args) {
    
            String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
            BufferedReader br = null;
            String line = "";
            String cvsSplitBy = ",";
            List list = new ArrayList();
    
            String[] country = null;
            Map hm = new HashMap();
            try {
    
                br = new BufferedReader(new FileReader(csvFile));
                while ((line = br.readLine()) != null) {
    
                    // use comma as separator
                    country = line.split(cvsSplitBy);
    
                    list.add(country[2]);
    
                    System.out.println(country[1]);
                }
                for (String i : list) {
                    Integer j = hm.get(i);
                    hm.put(i, (j == null) ? 1 : j + 1);
                }
                // displaying the occurrence of elements in the arraylist
                for (Map.Entry val : hm.entrySet()) {
                    if(val.getKey().equals("Error Message")){
                        System.out.println(val.getKey());
                        continue;
                    }
                    System.out.println(val.getKey() + " " + val.getValue());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

提交回复
热议问题