2014-01-12 69 views
0

我试图用扫描仪与形式的“A/B”部分字符串文本文件阅读,它们存储在一个数组,然后打印到控制台上沿每个唯一一个其计数。我可以用精确的计数打印文本文件中的每个单独条目,但我无法弄清楚如何在没有任何重复的情况下打印数组的内容。删除重复数组项

我也想完全主内做到这一点。下面是我到目前为止有:

公共静态无效的主要(字串[] args)抛出FileNotFoundException异常 {

ArrayList<String> fracs = new ArrayList<String>(); 
    Scanner input = new Scanner(new File("input.txt")); 
    ArrayList<String> fracsDisplay = new ArrayList<String>(); 

    while(input.hasNext()) 
     fracs.add(input.next()); 

    for(int i = 0; i < fracs.size(); i++) 
    { 
     int count = 0; 
     for(int j = 0; j < fracs.size(); j++) 
     { 
      if(fracs.get(i).equals(fracs.get(j))) 
       count++; 
     } 
     System.out.println(fracs.get(i) + ": " + count); 
    } 

    input.close(); 

}

+0

嗯,你可以添加的元素之前检查'fracs.contains(...)'如果数组包含已经是一个元素,如果是的话只是增加计数器或避免再次添加元素。一个'Set'默认情况下阻止重复条目。如果你想打印入口名称和数量,为什么不使用'Map'?通过独特的条目(=键)查找计(=值) –

回答

0

如果把握它,这个任务是“字数“的任务。为了完成这样的任务,HashMap是最好的选择。 我建议你使用HashMap来完成这个任务。你的算法的时间复杂度为O(n^2)。您可以使用HashMap将其减小到O(n)。使用HashMap也可以帮助您重复数据删除。哈瓦一试。

 HashMap<String, Integer> fracs = new HashMap<String, Integer>(); 
     Scanner input = new Scanner(new File("input.txt")); 

     while(input.hasNext()) { 
      String frac = input.next(); 
      if (! fracs.containsKey(frac)) { 
       fracs.put(frac, 1); 
      } else { 
       fracs.put(frac, fracs.get(frac) + 1); 
      } 
     } 

     input.close(); 

     for (Map.Entry<String, Integer> fracCount : fracs.entrySet()) { 
      System.out.println(fracCount.getKey() + " " + fracCount.getValue()); 
     } 

如果部分字符串应保持一次出现的顺序,使用LinkedHashMap的;如果分数字符串应保留字典顺序或某些精确的顺序,请使用SortedHashMap。在这里,我建议你阅读“Java泛型和集合”其中重点Java集合框架

0

是否应该将所有内容都存储到ArrayList中?您可以使用HashSetTreeSet,因为不允许发布。

0

最简单的方法来摆脱重复的将是使用Set,为您存储字符串复制不会被添加。

而不是ArrayList<String> fracsDisplay = new ArrayList<String>();你可以使用:

Set<String> fracsDisplay = new HashSet<>(); 
fracsDisplay.addAll(fracs); 
for (String s : fracsDisplay) { 
    System.out.println(s); 
} 

如果需要某种为了维持那么我会建议一个TreeSet,但无论是将处理去除重复的......这似乎是什么你想在这种情况下。

+0

缺点,如果项目应可在一个有序的结构 –

+0

诚然,在这种情况下,可以使用'TreeSet',OP没有说明订单是否很重要或不...答案更新,以反映你的建议! –

0

您可以使用HashSetSet集合不允许重复的值。如果您的阵列顺序很重要,那么您可以使用LinkedHashSet

Set<T> set = new HashSet<T>(); 
Collections.addAll(set, array);