Reputation: 39
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.
Upvotes: 0
Views: 692
Reputation: 954
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);
}
}
Upvotes: 2