0

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.

4

1 回答 1

2

这是一种更简单的方法:

    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);
    }
    }
于 2013-10-03T19:19:48.363 回答