2010-01-11 47 views
0

我在一个文件中管道并将其存储到树中。我正在计数独特的词.. 我把我不想成为一个哈希集的单词。我想要检查文件是否包含这些单词,然后我将它们放置到树集 .. 我知道我需要某种类型的if(word = = find)?我只是不知道该怎么做..在hashset或treeset中查找单词?

抱歉格式。粘贴后很难使其正确。

这就是我..

import java.util.Scanner; 
import java.util.ArrayList; 
import java.util.TreeSet; 
import java.util.Iterator; 
import java.util.HashSet; 

public class Project1 
{ 
    public static void main(String[] args) 
    { 
     Scanner  sc = new Scanner(System.in);  
     String  word; 
     String grab; 
     int count = 0; 
     int count2 =0; 
     int count3 =0; 
     int count4 =0; 
     int number; 
     TreeSet<String> a = new TreeSet<String>(); 
     HashSet<String> find = new HashSet<String>(); 

     System.out.println("Project 1\n"); 
     find.add("a"); 
     find.add("and"); 
     find.add("the"); 

     while (sc.hasNext()) 
     { 
      word = sc.next(); 
      word = word.toLowerCase(); 
      for(int i = 0; i < word.length(); i++) 
      { 
       if(Character.isDigit(word.charAt(i))) 
       { 
        count3++; 
       } 
      } 
      //if(a.contains("a")) 
      //|| word.matches("and") || word.matches("the")|| word.contains("$")) 
      //{ 
      // count2++; 
      // } 
      a.add(word); 
      if (word.equals("---")) 
      { 
       break; 
      } 
     } 

     System.out.println("a size"); 
     System.out.println(a.size()); 
     // count = count2 - count; 
     System.out.println("unique words"); 
     System.out.println(a.size() - count2 - count3); 
     System.out.println("\nbye..."); 
    } 
} 
+2

您可能想要阅读TreeSet文档http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html – 2010-01-11 02:15:37

回答

3

我看到你正在使用SO整个项目。

你可以做一些线沿线的:

if(!find.contains(word)){ 
    //addTheWord 
} 
+0

@anq - 谢谢.. – icelated 2010-01-11 02:41:29

1

这有点切你的问题,但它永远不会太早学习code to the interface。在你的榜样,

TreeSet<String> a = new TreeSet<String>(); 
HashSet<String> find = new HashSet<String>(); 

可能会更好,因为

Set<String> uniqueWords = new TreeSet<String>(); 
Set<String> trivialWords = new HashSet<String>(); 

使用的接口类型会将重点放在两个集合的Set功能。随着程序的发展,它还允许您在以后轻松地选择不同的实现。描述性名称也是一个好习惯。

+0

总是好的建议初学者!这个概念让我很早以前就爱上了它:节省打字和重构时间。 – anq 2010-01-12 04:59:48

0

要查找一个元素: HashSet的:使用含有()需要O(C) - 定时间 TreeSet的:使用含有()需要O(log n)的 - 日志N >> C(取决于)

如果经常需要查找元素的自然顺序,请使用TreeSet。否则,使用HashSet。