Cosmin
Cosmin

Reputation: 39

Words occurrence in linked list java

I have to do word occurrences in a linked list but without storing the words into a Map. I'm only allowed to use the linked list. The output: words, occurrence, percentage. Can someone help please ?

public class Linkedlist {

    private LinkedList<String> list = new LinkedList<String>();

    public void readFile() {

        File file = new File("words.txt");

        try {

            Scanner sc = new Scanner(file);

            String words;

            while (sc.hasNext()) {
                words = sc.next();
                words = words.toLowerCase();
                Collections.sort(list);

                if (words.length() >= 2) {
                    if (list.contains(words)) {


                }
            }

            sc.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void showList() {
        System.out.println(list);
    }

    public static void main(String args[]) {

        Linkedlist abc = new Linkedlist();

        abc.readFile();
        abc.showList();
    }
}

Upvotes: 1

Views: 1166

Answers (2)

Mohan Raj
Mohan Raj

Reputation: 1132

    try {
        Scanner sc = new Scanner(file);
        String words;          
        while (sc.hasNext()) {
            words = sc.next().toLowerCase();
            list.add(words);  
         } 
        Scanner sc1=new Scanner(file);
        int i=0;
        while (sc1.hasNext()) {
             words = sc1.next().toLowerCase();              
            double count=0;
         while(i<list.size()){
            if(list.get(i).equalsIgnoreCase(words)){
                  count++;
                   i++;
            }

            else                    
                 break;             
        }
        if(count !=0)
         System.out.println(words+" "+(Double)count/list.size());

        }

        sc.close();
        sc1.close();
    }

Modify the try block as above Hope the code is self explanatory.

Ouput:

  car 0.5
  van 0.25
  bus 0.25
  [car, car, van, bus]

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

Something like this should work

    Collections.sort(words);
    String last = null;
    int n = 0;
    for (String w : words) {
            if (w.equals(last)) {
                n++;
            } else {
                if (last != null) {
                    System.out.printf("%s %d %.1f%%%n", last,  n, 100.0 * n / words.size());
                }
                last = w;
                n = 1;
            }
    }
    System.out.printf("%s %d %.1f%%%n", last,  n, 100.0 * n / words.size()); 

Upvotes: 2

Related Questions