总结哈希表值Java

时间:2014-07-06 08:55:06

标签: java hashtable

我有hashtable<String, Double>计算单词出现次数的作业。我发现许多在线代码都运行得很好,但问题是:

如何将所有出现的内容汇总在一起,例如,如果我有三个单词出现:

train = 2
java = 1
master = 4

我想得到这些事件的总和,例如Sum = 2 + 1 + 4 = 7

我在控制台中使用此行

获得的这些出现值
hashtable.get(key);

现在当我创建一个变量来存储hashtable.get(key)我得到错误时,不能将double转换为int。

使用

时出现同样的错误
hashtable.get(key).intValue();

这是我的整个代码......

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class main {
    static final Integer ONE = new Integer(1);
    public static String path;
    public static String path1;
    public static String path2;
    public static String nazivRjecnika;
    public static String key;
    public static int Suma, Suma1, Suma2, Suma3 = 0;
    public static int aj;

    public static void main(String[] args) throws IOException {


        String pathPolitika = "C:/Users/Lulu-Debela/Desktop/New folder/POLITIKA";   
        String pathShowbiz = "C:/Users/Lulu-Debela/Desktop/New folder/SHOWBIZ";
        String pathSport = "C:/Users/Lulu-Debela/Desktop/New folder/SPORT";
        String pathPRjecnik = "C:/Users/Lulu-Debela/Desktop/New folder/POLITIKA/rjecnik.txt";
        String pathShRjecnik = "C:/Users/Lulu-Debela/Desktop/New folder/SHOWBIZ/rjecnik.txt";
        String pathSRjecnik = "C:/Users/Lulu-Debela/Desktop/New folder/SPORT/rjecnik.txt";
        String pathPolitikaRjecnik = "C:/Users/Lulu-Debela/Desktop/New folder/POLITIKA/rjecnik_politika.txt";           
        String pathShowbizRjecnik = "C:/Users/Lulu-Debela/Desktop/New folder/SHOWBIZ/rjecnik_showbiz.txt";  
        String pathSportRjecnik = "C:/Users/Lulu-Debela/Desktop/New folder/SPORT/rjecnik_sport.txt";    
        String line = null;
        int ngramOffset = 3;        
        String files;

        for (int g=0; g<3; g++){
            if(g==0){
                path = pathPolitika;
                path1 = pathPRjecnik;
                path2 = pathPolitikaRjecnik;
                nazivRjecnika = "rjecnik_politika.txt";
            }
            else if(g==1){
                path = pathShowbiz;
                path1 = pathShRjecnik;
                path2 = pathShowbizRjecnik;
                nazivRjecnika = "rjecnik_showbiz.txt";
            }
            else if(g==2){
                path = pathSport;
                path1 = pathSRjecnik;
                path2 = pathSportRjecnik;
                nazivRjecnika = "rjecnik_sport.txt";
            }
                File folder = new File(path);
                File oldrjecnik = new File (path1);
                File oldrjecniktrigram = new File (path2);
                File[] listOfFiles = folder.listFiles();

                oldrjecnik.delete();
                oldrjecniktrigram.delete();

                for (int i = 0; i<listOfFiles.length; i++){

                    if (listOfFiles[i].isFile()){

                        files = listOfFiles[i].getName();

                            if (files.endsWith(".txt")|| files.endsWith(".TXT")){

                                if(!files.startsWith("rjecnik.txt")&&!files.startsWith(nazivRjecnika)){

                                    File textFile = new File(folder.getAbsolutePath()+ File.separator + files);

                                    try{

                                        BufferedReader br = new BufferedReader(new FileReader(textFile));
                                        BufferedWriter writer = new BufferedWriter(new FileWriter(path1, true));
                                        String sCurrentLine;
                                            while ((sCurrentLine = br.readLine()) != null) {
                                                line = sCurrentLine;
                                                    for (String ngram : ngrams(ngramOffset, line))  
                                                        writer.write(ngram + "\r\n");
                                                    }
                                                            br.close();
                                                            writer.close();

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

                                } 
                            }
                    }
                }
                    Hashtable<String, Double> hashtable = new Hashtable<String, Double>();
                    BufferedWriter writer = new BufferedWriter(new FileWriter(path2, true));
                    FileReader fr = new FileReader(path1);
                    BufferedReader br = new BufferedReader(fr);
                    String linee;
                    double p=0;
                        while ((linee = br.readLine()) != null) {
                            processLine(linee, hashtable);
                            }   
                                Enumeration e = hashtable.keys();
                                    while (e.hasMoreElements()) {
                                        key = (String) e.nextElement();
                                        writer.write(key + " : " + hashtable.get(key) + "\r\n");                                
                                        hashtable.get(key);
                                        }
                                            p = hashtable.get(key).intValue(); //Here is the error I get
                                            System.out.println(p);
                                            writer.close();
                                            br.close();
                                            oldrjecnik.delete();



        }


    }


      static void processLine(String line, Map map) {
          addWord(map, line);
      }

      static void addWord(Map map, String word) {
        Object obj = map.get(word);
        if (obj == null) {
          map.put(word, ONE);
        } else {
          int i = ((Integer) obj).intValue() + 1;
          map.put(word, new Integer(i));
        }

    public static int countLines(String filename) throws IOException {
        InputStream is = new BufferedInputStream(new FileInputStream(filename));
        try {
            byte[] c = new byte[1024];
            int count = 0;
            int readChars = 0;
            boolean empty = true;
            while ((readChars = is.read(c)) != -1) {
                empty = false;
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == '\n') {
                        ++count;
                    }
                }
            }
            return (count == 0 && !empty) ? 1 : count;
        } finally {
            is.close();
        }
    }


    public static List<String> ngrams(int n, String str) {
        List<String> ngrams = new ArrayList<String>();
        String[] words = str.split(" ");
        for (int i = 0; i < words.length - n + 1; i++)
            ngrams.add(concat(words, i, i+n));
        return ngrams;
    }

    public static String concat(String[] words, int start, int end) {
        StringBuilder sb = new StringBuilder();
        for (int i = start; i < end; i++)
            sb.append((i > start ? " " : "") + words[i]);
        return sb.toString();
    }
}

...这就是我得到的错误:

`Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
at main.main(main.java:125)`

3 个答案:

答案 0 :(得分:0)

这里是计算单词的代码。

我不明白为什么你使用双打,然后你会计算单词。如果你计算单词,你将使用整数。然后你就没有铸造问题了。

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class WordCount {
  public static void main(String[] args) throws IOException {
    Map<String, Integer> wordMap = new HashMap<>();
//    BufferedWriter writer = new BufferedWriter(new FileWriter(path2, true));
    StringWriter stringWriter = new StringWriter();
    BufferedWriter  writer = new BufferedWriter(stringWriter);

//    BufferedReader br = new BufferedReader(new FileReader(path1));
    BufferedReader br = new BufferedReader(new StringReader("hello this is a test test     a test"));

    String line;
    while ((line = br.readLine()) != null){
      String[] words = lineToWords(line);
      addWords(words, wordMap);
    }

    for (Map.Entry<String, Integer> wordCountEntry : wordMap.entrySet()) {
      writer.write(wordCountEntry.getKey() + " : " + wordCountEntry.getValue() + "\r\n");
    }

    writer.close();
    br.close();

    System.out.println(stringWriter);
  }

  static String[] lineToWords(String line){
    StringTokenizer tokenizer = new StringTokenizer(line, " ", false);
    String[] words = new String[tokenizer.countTokens()];
    for (int i = 0; i < words.length; i++) {
      words[i] = tokenizer.nextToken();
    }

    return words;
  }

  static void addWords(String[] words, Map<String, Integer> wordMap){
    for (String word : words) {
      addWord(word, wordMap);
    }
 }

  static void addWord(String word, Map<String, Integer> wordMap){
    Integer integer = wordMap.get(word);
    if(integer == null){
      integer = 0;
    }

    wordMap.put(word, integer + 1);
  }
}

答案 1 :(得分:0)

转过这一行:

int i = ((Integer) obj).intValue() + 1;

进入这一行:

int i = ((Double) obj).intValue() + 1;

我不确定你为什么要使用双打来计算单词。

答案 2 :(得分:0)

此问题的根源是raw types的使用:

static void addWord(Map map, String word) {

Hashtable<String, Double>传递给此方法时,会丢失有关类型参数的信息。这就是为什么以下行编译得很好的原因:

map.put(word, new Integer(i));

如果您更改了方法签名,则不要使用这样的原始类型:

static void addWord(Map<String, Double> map, String word) {

您可以在编译时捕获此问题。

如果你看一下Hashtable#get的实现,你会注意到它确实是一种类型转换:

return (V)e.value;

DoubleInteger是不同的类(不要将它们与原语doubleint混淆),其中没有一个继承其他类(它们两者都延伸Number,所以你得到ClassCastException