2014-07-06 3 views
-3

hashtable<String, Double>에 단어 수를 계산하도록 지정했습니다. 난 그냥 잘 작동 많은 코드 온라인을 발견하지만, 문제는 이것이다 :해시 테이블 값 합계

모두 함께 나는 그들의 발생과 세 단어가있는 경우, 예를 들어 발생이를 합계하는 방법

:

train = 2 
java = 1 
master = 4 

나는 합계를 가지고 싶어 이 합계와 같은 그 발생 = 2 + 1 + 4 = 7

발생이 값을 내가 변수를 만들 때 내가

hashtable.get(key); 

이제이 줄을 콘솔에서 얻을 그것을 저장하려면 hashtable.get(key) 오류가 발생하면 int로 double을 캐스팅 할 수 없습니다.

내가

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)` 
+0

'p' 선언문을 추가하고 문제의 실행 가능한 예제를 만들 수 있습니까? – Jens

+1

정확한 스택 추적은 무엇입니까? 스택 트레이스가 가리키는 라인을 포함하여 게시하십시오. – Unihedron

+3

그리고 그건 분명히 "전체 코드"가 아닙니다. 수입? 클래스 선언? 짧지 만 완전한 프로그램은 정말로 도움이 될 것입니다 ... 다음으로, 당신이 아마도 Hashtable 를 원할 때'Hashtable '을 생성하고 있다는 것에 주목하십시오. (왜 Hashmap 대신 Hashtable을 사용합니까?) –

답변

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

를 켭이 라인 :

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

이 줄에 : 당신이 비록 단어를 계산하는 복식을 사용하는 이유

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

는 잘 모르겠어요.

+0

오른쪽. 왜냐하면 Integer는 Double의 서브 클래스가 아니고 Double은 Integer의 서브 클래스가 아니기 때문에 Double을 정수로 형변환 할 수 없기 때문입니다. 하지만 int에 double을 캐스팅 할 수 있습니다. – schlagi123

+0

안녕하세요, 답변을위한 thx 나는 이미 이것을 시도하고 여전히 캔트 int 던져 오류가 점점. 그래서 해시 테이블을 로 바꿀 수는 있지만 작동 할 것이지만 할당은 해시 테이블 을 만드는 것입니다. – user3809187

0

이 문제의 기원은 raw types의 사용이다 : 당신은 당신이 방법 Hashtable<String, Double>, 당신은 입력 매개 변수에 대한 정보를 잃게 통과

static void addWord(Map map, String word) { 

. 다음 줄은 잘 컴파일 이유 :

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

이 같은 원시 타입을 사용하지 않는 방법 서명을 변경 한 경우 :

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

당신은 컴파일 시간에이 문제를 잡을 수있을 것입니다.,

return (V)e.value; 

DoubleInteger가 다른 클래스 (프리미티브 doubleint 그들을 혼동하지 마십시오)입니다

당신은 당신이 타입 캐스팅이 실제로 거기에 알, Hashtable#get의 구현을 살펴 경우 그들 중 아무도 다른 쪽에서 상속받습니다 (그들은 모두 Number을 확장합니다). 따라서 ClassCastException이됩니다.