简体   繁体   English

计算文件中的单词并将其存储在数组中?

[英]counting words of a file and storing it in array?

again. 再次。 im gonna ask again about counting words and how to store it in array. 我将再次询问有关单词计数以及如何将其存储在数组中的问题。 So far, all i got is this. 到目前为止,我所得到的只是这个。

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) {

my code works. 我的代码有效。 but my question is, is there a more simple way to this? 但是我的问题是,有没有更简单的方法呢? And the other question is how do i count the unique words out of the total words in a given file without using hashmap and arraylist. 另一个问题是如何在不使用哈希图和数组列表的情况下,在给定文件的总字数中计算唯一字。

Heres a simpler way to go about it: 这是一种更简单的解决方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM