链表java中的单词出现

时间:2015-05-07 11:53:02

标签: java

我必须在链接列表中进行单词出现,但不将单词存储到Map中。我只允许使用链表。输出:单词,出现,百分比。有人可以帮忙吗?

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();
    }
}

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效

    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()); 

答案 1 :(得分:0)

    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();
    }
  
    

如上所述修改try块希望代码是自我解释的。

  

输出继电器:

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