计数文件的文字并将其存储在数组中?

问题描述:

。我会再问一次关于计算单词以及如何将它存储在数组中的方法。到目前为止,我得到的只是这个。计数文件的文字并将其存储在数组中?

Scanner sc = new Scanner(System.in); 
int count; 
void readFile() { 
System.out.println("Gi navnet til filen: "); 
String filNavn = sc.next(); 

try{ 
    File k = new File(filNavn); 
    Scanner sc2 = new Scanner(k); 
    count = 0; 
    while(sc2.hasNext()) { 
    count++; 
    sc2.next(); 
    } 
    Scanner sc3 = new Scanner(k); 
    String a[] = new String[count]; 
    for(int i = 0;i<count;i++) { 
    a[i] =sc3.next(); 
    if (i == count -1) { 
     System.out.print(a[i] + "\n"); 
    }else{ 
     System.out.print(a[i] + " "); 
    } 
    } 
    System.out.println("Number of words: " + count); 
}catch(FileNotFoundException e) { 

我的代码有效。但我的问题是,是否有更简单的方法呢?另一个问题是,如何在不使用散列表和数组列表的情况下对给定文件中的单词进行统计。

+1

是HashSet的一个选择吗? – Pshemo

+0

您可以使用'Arrays.copyOf(Object [],int)'方法在遇到另一个字符串时为其添加空间。这是'ArrayList'的工作方式。 – Obicere

+0

使用Arralylist来存储单词并使用BuffereReader逐行读取使用'readline()'函数的文件并将它们拆分为数组的单词。 – Sage

继承人一个简单的方法去做:

public static void main(String[] args){ 
    File f= new File(filename); 
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); 
    String line = null; 
    String[] res; 
    while((line = br.readLine())!= null){ 
     String[] tokens = line.split("\\s+"); 
     String[] both = ArrayUtils.addAll(res, tokens); 
    } 
    } 
+1

也可以用@Pshemo来计算一个唯一的单词,你可以使用HashSet。 HashSet是一个没有重复元素的集合。所以你的HashSet的大小将被计数。 –

+0

我们不允许使用hashset,map和arraylist –

+0

您可以在插入前使用“contains”方法。 –