-1

I need to count number of occurences of the same strings in txt file.

What I have come up with is

public class CountWords {
public File file;
public Scanner scan = null;
public LinkedHashMap<String, Integer> list = new LinkedHashMap<>();

public CountWords(String txt) {
    file = new File(txt);
}

public void textEdit() {

    try {
        scan = new Scanner(file);
    } catch (FileNotFoundException e) {
        System.out.println("----");
    }

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        if(!list.containsKey(line))
            list.put(scan.next(),1);
        else {
            list.put(line,list.get(line)+1);
        }
    }
    scan.close();
}
public List<String> getResult(){
    textEdit();
    return list;
}

the class Main shouldn't be changed in any way (that is the requirement) and the output should be in the same order as input (that's why LinkedHashMap is used)

public class Main {
    public static void main(String[] args) throws Exception {
        String fname = System.getProperty("user.home") + "/textforwords.txt";
        CountWords cw = new CountWords(fname);
        List<String> result = cw.getResult();
        for (String wordRes : result) {
            System.out.println(wordRes);
        }
    }
}

I missed something that I can't figure out.

SaeX
  • 17,240
  • 16
  • 77
  • 97
Yun8483
  • 27
  • 4
  • Does this compile? getResult is declared to return a List but you are returning a LinkedHashMap. – JimmyJames Mar 23 '16 at 19:46
  • @JimmyJames no and this is the place where I have confused I need to connect this two things somehow, because the requirement were "not to change Main" and "use LinkedHashMap" – Yun8483 Mar 23 '16 at 19:55
  • What kind of strings should the list returned by `getResult()` contain? Do you got a specification for this? – vanje Mar 23 '16 at 20:15

1 Answers1

0

You need a count of strings or lines?

If you need to count of strings, try this:

while (scan.hasNext()) {
    String line = scan.next();
    if(!list.containsKey(line))
        list.put(line,1);
    else {
        list.put(line,list.get(line)+1);
    }
}

And getResult you can modify like this:

public List<String> getResult(){
    textEdit();

    ArrayList<String> result = new ArrayList<>();
    for(Map.Entry<String, Integer> entry : list.entrySet()){
        result.add(entry.getKey() + " " + entry.getValue());
    }
    return result;
}

P.S. I can not add a comment